List of usage examples for com.google.common.base Stopwatch toString
@GwtIncompatible("String.format()") @Override public String toString()
From source file:com.sri.ai.praise.lang.translate.cli.RunTranslationsCLI.java
/** * Translate Probabilistic Models based on given command line arguments. * /*ww w .j ava2 s . c o m*/ * @param args * pass '--help' to see description of expected program arguments. */ public static void main(String[] args) { TranslationArgs translationArgs = getArgs(args); for (Translator translator : translationArgs.translators) { File sourceDirectory = new File(translationArgs.rootModelOutputDirectory, translator.getSource().getCode()); if (!sourceDirectory.isDirectory()) { throw new IllegalArgumentException("Source Directory " + sourceDirectory + " does not exist"); } File targetDirectory = new File(translationArgs.rootModelOutputDirectory, translator.getTarget().getCode()); if (!targetDirectory.isDirectory()) { targetDirectory.mkdir(); } String sourceModelFileExtension = translator.getInputFileExtensions()[0]; for (File sourceModelFile : sourceDirectory .listFiles((dir, name) -> name.endsWith(sourceModelFileExtension))) { System.out.println("Translating " + sourceModelFile.getName() + " from " + translator.getSource().getCode() + " to " + translator.getTarget().getCode()); String sourceModelFileNameWithNoExtension = translator .getInputModelFileNameWithNoExtension(sourceModelFile); Stopwatch sw = Stopwatch.createStarted(); try (InputModelReaders inputModelReaders = new InputModelReaders(translator, sourceModelFile, sourceModelFileExtension); TranslatedOutputs translatedOutputs = new TranslatedOutputs(translator, sourceModelFile, sourceModelFileExtension)) { translator.translate(sourceModelFileNameWithNoExtension, inputModelReaders.readers, translatedOutputs.writers, new TranslatorOptions()); } catch (Exception ex) { System.err.println("Error during translation"); ex.printStackTrace(); System.exit(-1); } sw.stop(); System.out.println("Took " + sw.toString()); // TODO - append the time it took to translate the file to a .csv file } } }
From source file:cosmos.example.BuildingPermitsExample.java
public static void main(String[] args) throws Exception { BuildingPermitsExample example = new BuildingPermitsExample(); new JCommander(example, args); File inputFile = new File(example.fileName); Preconditions.checkArgument(inputFile.exists() && inputFile.isFile() && inputFile.canRead(), "Expected " + example.fileName + " to be a readable file"); String zookeepers;//from w w w . ja v a 2 s. com String instanceName; Connector connector; MiniAccumuloCluster mac = null; File macDir = null; // Use the MiniAccumuloCluster is requested if (example.useMiniAccumuloCluster) { macDir = Files.createTempDir(); String password = "password"; MiniAccumuloConfig config = new MiniAccumuloConfig(macDir, password); config.setNumTservers(1); mac = new MiniAccumuloCluster(config); mac.start(); zookeepers = mac.getZooKeepers(); instanceName = mac.getInstanceName(); ZooKeeperInstance instance = new ZooKeeperInstance(instanceName, zookeepers); connector = instance.getConnector("root", new PasswordToken(password)); } else { // Otherwise connect to a running instance zookeepers = example.zookeepers; instanceName = example.instanceName; ZooKeeperInstance instance = new ZooKeeperInstance(instanceName, zookeepers); connector = instance.getConnector(example.username, new PasswordToken(example.password)); } // Instantiate an instance of Cosmos Cosmos cosmos = new CosmosImpl(zookeepers); // Create a definition for the data we want to load Store id = Store.create(connector, new Authorizations(), AscendingIndexIdentitySet.create()); // Register the definition with Cosmos so it can track its progress. cosmos.register(id); // Load all of the data from our inputFile LoadBuildingPermits loader = new LoadBuildingPermits(cosmos, id, inputFile); loader.run(); // Finalize the SortableResult which will prevent future writes to the data set cosmos.finalize(id); // Flush the ingest traces to the backend so we can see the results; id.sendTraces(); // Get back the Set of Columns that we've ingested. Set<Column> schema = Sets.newHashSet(cosmos.columns(id)); log.debug("\nColumns: " + schema); Iterator<Column> iter = schema.iterator(); while (iter.hasNext()) { Column c = iter.next(); // Remove the internal ID field and columns that begin with CONTRACTOR_ if (c.equals(LoadBuildingPermits.ID) || c.name().startsWith("CONTRACTOR_")) { iter.remove(); } } Iterable<Index> indices = Iterables.transform(schema, new Function<Column, Index>() { @Override public Index apply(Column col) { return Index.define(col); } }); // Ensure that we have locality groups set as we expect log.info("Ensure locality groups are set"); id.optimizeIndices(indices); // Compact down the data for this SortableResult log.info("Issuing compaction for relevant data"); id.consolidate(); final int numTopValues = 10; // Walk through each column in the result set for (Column c : schema) { Stopwatch sw = new Stopwatch(); sw.start(); // Get the number of times we've seen each value in a given column CloseableIterable<Entry<RecordValue<?>, Long>> groupingsInColumn = cosmos.groupResults(id, c); log.info(c.name() + ":"); // Iterate over the counts, collecting the top N values in each column TreeMap<Long, RecordValue<?>> topValues = Maps.newTreeMap(); for (Entry<RecordValue<?>, Long> entry : groupingsInColumn) { if (topValues.size() == numTopValues) { Entry<Long, RecordValue<?>> least = topValues.pollFirstEntry(); if (least.getKey() < entry.getValue()) { topValues.put(entry.getValue(), entry.getKey()); } else { topValues.put(least.getKey(), least.getValue()); } } else if (topValues.size() < numTopValues) { topValues.put(entry.getValue(), entry.getKey()); } } for (Long key : topValues.descendingKeySet()) { log.info(topValues.get(key).value() + " occurred " + key + " times"); } sw.stop(); log.info("Took " + sw.toString() + " to run query.\n"); } log.info("Deleting records"); // Delete the records we've ingested if (!example.useMiniAccumuloCluster) { // Because I'm lazy and don't want to wait around to run the BatchDeleter when we're just going // to rm -rf the directory in a few secs. cosmos.delete(id); } // And shut down Cosmos cosmos.close(); log.info("Cosmos stopped"); // If we were using MAC, also stop that if (example.useMiniAccumuloCluster && null != mac) { mac.stop(); if (null != macDir) { FileUtils.deleteDirectory(macDir); } } }
From source file:uk.ac.liverpool.narrative.BranchingStoryGenerator.java
public static void main(String args[]) { // try {Thread.sleep(10000); ///*from w ww . ja v a2 s.co m*/ // } catch (Exception x) {}; Stopwatch s = new Stopwatch(); s.start(); EPSILON = EPSILON.setScale(2, BigDecimal.ROUND_HALF_EVEN); MAX_DURATION = MAX_DURATION.setScale(2, BigDecimal.ROUND_HALF_EVEN); BranchingStoryGenerator planner = new BranchingStoryGenerator(); planner.current = Thread.currentThread(); JCommander jc = new JCommander(planner); jc.setProgramName("BranchingStoryGenerator"); try { jc.parse(args); } catch (ParameterException x) { jc.usage(); usage(); System.out.println(x.getMessage()); System.exit(-1); } usage(); // reminder: this seems to rule out many new solutions when run on // branching EHCSearch! So leave to false // check planner.doFilterReachableFacts = false; System.out.println("Current invocation:"); CURRENT_ARGS = Arrays.toString(args); System.out.println(CURRENT_ARGS); if (planner.domainFilePath == null || planner.problemFilePath == null || planner.templateFilePath == null) { // usage(); System.exit(-1); } planner.post_process_options(); planner.plan(planner.problemFile); System.out.println("Planning took: " + s.toString()); }
From source file:cc.kave.commons.pointsto.evaluation.PointsToEvaluation.java
private static void generateUsages(List<PointsToAnalysisFactory> factories) { try {/*w w w.ja va 2 s . c om*/ Function<PointsToAnalysisFactory, UsageStore> usageStoreFactory = (PointsToAnalysisFactory factory) -> { try { return new ProjectUsageStore(USAGE_DEST.resolve(factory.getName())); } catch (Exception e) { throw new RuntimeException(e); } }; DescentStrategy descentStrategy = new SimpleDescentStrategy(); PointsToUsageGenerator generator = new PointsToUsageGenerator(factories, SRC_PATH, null, usageStoreFactory, new TypeStatisticsCollector(new PointsToUsageFilter()), descentStrategy); Stopwatch stopwatch = Stopwatch.createStarted(); generator.generateUsages(); stopwatch.stop(); LOGGER.info("Usage generation took {}", stopwatch.toString()); outputStatisticsCollectors(generator.getStatisticsCollectors()); } catch (IOException e) { LOGGER.error("Error during usage generation", e); } }
From source file:de.nx42.maps4cim.MapGenerator.java
/** * Launches the map generator using the specified configuration * and writes the resulting map to the specified file. * * Returns true, iff the map was generated without errors. * * @param conf the map is generated based on the information provided in * this config/*w w w . j a va 2 s. co m*/ * @param dest the file where the resulting map is written to * @return true, iff the map was generated without errors */ public static boolean execute(Config conf, File dest) { try { final Stopwatch stopwatch = Stopwatch.createStarted(); log.info("Map Generator has been started."); MapGenerator mg = new MapGenerator(conf); try { log.debug("Ressources initialized. The map will now be written..."); Result res = mg.generateMap(dest); stopwatch.stop(); if (res.isSuccess()) { log.info("The map has been successfully generated. Total Time: {}", stopwatch.toString()); logAttribution(conf); return true; } else { log.warn(res.getReport()); log.warn("Something went wrong, so your map has been generated " + "in fallback mode (probably it's just empty).\n" + "Please review the errors and post this log in the " + "forums if you are not sure how to fix them."); return false; } } catch (MapGeneratorException e) { // errors are already logged return false; } } catch (Exception e) { log.error("Unexpected Exception", e); return false; } }
From source file:org.sonatype.nexus.repository.view.handlers.TimingHandler.java
@Nonnull @Override//from w w w . j av a2 s. c o m public Response handle(@Nonnull final Context context) throws Exception { Stopwatch watch = Stopwatch.createStarted(); try { return context.proceed(); } finally { String elapsed = watch.toString(); context.getAttributes().set(ELAPSED_KEY, elapsed); log.trace("Timing: {}", elapsed); } }
From source file:fi.helsinki.moodi.integration.http.RequestTimingInterceptor.java
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { Stopwatch stopwatch = Stopwatch.createStarted(); ClientHttpResponse response = execution.execute(request, body); stopwatch.stop();/* w ww .ja va 2 s .co m*/ log.info(String.format("Requesting uri %s took %s", request.getURI(), stopwatch.toString())); return response; }
From source file:org.sonatype.sisu.bl.servlet.jetty.testsuite.JettyRunningITSupport.java
@Before public void beforeTestIsRunning() { final Stopwatch stopwatch = startJetty(jetty()); testIndex().recordInfo("startup time", stopwatch.elapsed(TimeUnit.MILLISECONDS) == 0 ? "already running" : stopwatch.toString()); assertThat("Jetty is running before test starts", jetty().isRunning(), is(true)); }
From source file:org.sonatype.sisu.bl.testsupport.DropwizardRunningITSupport.java
@Before public void beforeTestIsRunning() { final Stopwatch stopwatch = startBundle(bundle()); testIndex().recordInfo("startup time", stopwatch.elapsed(TimeUnit.MILLISECONDS) == 0 ? "already running" : stopwatch.toString()); assertThat("Dropwizard bundle was not in running state", bundle().isRunning(), is(true)); }
From source file:com.b2international.snowowl.snomed.reasoner.server.normalform.ConceptConcreteDomainNormalFormGenerator.java
public void collectNormalFormChanges(final IProgressMonitor monitor, final OntologyChangeProcessor<ConcreteDomainFragment> processor) { LOGGER.info(">>> Concept concrete domain entry normal form generation"); final Stopwatch stopwatch = Stopwatch.createStarted(); collectNormalFormChanges(monitor, processor, ConcreteDomainChangeOrdering.INSTANCE); LOGGER.info(MessageFormat.format("<<< Concept concrete domain entry normal form generation [{0}]", stopwatch.toString())); }