List of usage examples for com.google.common.base Stopwatch createStarted
@CheckReturnValue public static Stopwatch createStarted()
From source file:eu.amidst.huginlink.examples.learning.ParallelPCExample.java
public static void main(String[] args) throws Exception { //We load a Bayesian network to generate a data stream //using BayesianNewtorkSampler class. int sampleSize = 100000; BayesianNetwork bn = BayesianNetworkLoader.loadFromFile("networks/dataWeka/Pigs.bn"); BayesianNetworkSampler sampler = new BayesianNetworkSampler(bn); //We fix the number of samples in memory used for performing the structural learning. //They are randomly sub-sampled using Reservoir sampling. int samplesOnMemory = 5000; //We make different trials with different number of cores ArrayList<Integer> vNumCores = new ArrayList(Arrays.asList(1, 2, 3, 4)); for (Integer numCores : vNumCores) { System.out// w w w. j av a 2s . c o m .println("Learning PC: " + samplesOnMemory + " samples on memory, " + numCores + " core/s ..."); DataStream<DataInstance> data = sampler.sampleToDataStream(sampleSize); //The class ParallelTAN is created ParallelPC parallelPC = new ParallelPC(); //We activate the parallel mode. parallelPC.setParallelMode(true); //We set the number of cores to be used for the structural learning parallelPC.setNumCores(numCores); //We set the number of samples to be used for the learning the structure parallelPC.setNumSamplesOnMemory(samplesOnMemory); Stopwatch watch = Stopwatch.createStarted(); //We just invoke this mode to learn a BN model for the data stream BayesianNetwork model = parallelPC.learn(data); System.out.println(watch.stop()); } }
From source file:com.google.devtools.build.android.RClassGeneratorAction.java
public static void main(String[] args) throws Exception { final Stopwatch timer = Stopwatch.createStarted(); OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class); if (args.length == 1 && args[0].startsWith("@")) { args = Files.readAllLines(Paths.get(args[0].substring(1)), StandardCharsets.UTF_8) .toArray(new String[0]); }/*from w w w. j a v a2 s . co m*/ optionsParser.parseAndExitUponError(args); Options options = optionsParser.getOptions(Options.class); Preconditions.checkNotNull(options.classJarOutput); final AndroidResourceProcessor resourceProcessor = new AndroidResourceProcessor(STD_LOGGER); try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("android_res_compile_tmp")) { Path tmp = scopedTmp.getPath(); Path classOutPath = tmp.resolve("compiled_classes"); LOGGER.fine(String.format("Setup finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); List<SymbolFileProvider> libraries = new ArrayList<>(); for (DependencySymbolFileProvider library : options.libraries) { libraries.add(library); } // Note that we need to write the R class for the main binary (so proceed even if there // are no libraries). if (options.primaryRTxt != null) { String appPackageName = options.packageForR; if (appPackageName == null) { appPackageName = VariantConfiguration.getManifestPackage(options.primaryManifest.toFile()); } Multimap<String, SymbolLoader> libSymbolMap = ArrayListMultimap.create(); SymbolLoader fullSymbolValues = resourceProcessor.loadResourceSymbolTable(libraries, appPackageName, options.primaryRTxt, libSymbolMap); LOGGER.fine(String.format("Load symbols finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); // For now, assuming not used for libraries and setting final access for fields. if (fullSymbolValues != null) { resourceProcessor.writePackageRClasses(libSymbolMap, fullSymbolValues, appPackageName, classOutPath, true /* finalFields */); LOGGER.fine(String.format("Finished R.class at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); } } else { Files.createDirectories(classOutPath); } // We write .class files to temp, then jar them up after (we create a dummy jar, even if // there are no class files). resourceProcessor.createClassJar(classOutPath, options.classJarOutput); LOGGER.fine(String.format("createClassJar finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); } finally { resourceProcessor.shutdown(); } LOGGER.fine(String.format("Compile action done in %sms", timer.elapsed(TimeUnit.MILLISECONDS))); }
From source file:com.google.devtools.build.android.AarGeneratorAction.java
public static void main(String[] args) { Stopwatch timer = Stopwatch.createStarted(); OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class); optionsParser.parseAndExitUponError(args); Options options = optionsParser.getOptions(Options.class); checkFlags(options);/*from w w w. j av a 2 s .com*/ AndroidResourceProcessor resourceProcessor = new AndroidResourceProcessor( new StdLogger(com.android.utils.StdLogger.Level.VERBOSE)); try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("aar_gen_tmp")) { Path tmp = scopedTmp.getPath(); Path resourcesOut = tmp.resolve("merged_resources"); Files.createDirectories(resourcesOut); Path assetsOut = tmp.resolve("merged_assets"); Files.createDirectories(assetsOut); logger.fine(String.format("Setup finished at %dms", timer.elapsed(TimeUnit.MILLISECONDS))); // There aren't any dependencies, but we merge to combine primary resources from different // res/assets directories into a single res and single assets directory. MergedAndroidData mergedData = resourceProcessor.mergeData(options.mainData, ImmutableList.<DependencyAndroidData>of(), ImmutableList.<DependencyAndroidData>of(), resourcesOut, assetsOut, null, VariantType.LIBRARY, null); logger.fine(String.format("Merging finished at %dms", timer.elapsed(TimeUnit.MILLISECONDS))); writeAar(options.aarOutput, mergedData, options.manifest, options.rtxt, options.classes); logger.fine(String.format("Packaging finished at %dms", timer.elapsed(TimeUnit.MILLISECONDS))); } catch (IOException | MergingException e) { logger.log(Level.SEVERE, "Error during merging resources", e); System.exit(1); } System.exit(0); }
From source file:eu.amidst.huginlink.examples.learning.ParallelTANExample.java
public static void main(String[] args) throws Exception { //We load a Bayesian network to generate a data stream //using BayesianNewtorkSampler class. int sampleSize = 100000; BayesianNetwork bn = BayesianNetworkLoader.loadFromFile("networks/dataWeka/Pigs.bn"); BayesianNetworkSampler sampler = new BayesianNetworkSampler(bn); //We fix the number of samples in memory used for performing the structural learning. //They are randomly sub-sampled using Reservoir sampling. int samplesOnMemory = 5000; //We make different trials with different number of cores ArrayList<Integer> vNumCores = new ArrayList(Arrays.asList(1, 2, 3, 4)); for (Integer numCores : vNumCores) { System.out.println(/* w w w . jav a 2 s . c om*/ "Learning TAN: " + samplesOnMemory + " samples on memory, " + numCores + " core/s ..."); DataStream<DataInstance> data = sampler.sampleToDataStream(sampleSize); //The class ParallelTAN is created ParallelTAN tan = new ParallelTAN(); //We activate the parallel mode. tan.setParallelMode(true); //We set the number of cores to be used for the structural learning tan.setNumCores(numCores); //We set the number of samples to be used for the learning the structure tan.setNumSamplesOnMemory(samplesOnMemory); //We set the root variable to be first variable tan.setNameRoot(bn.getVariables().getListOfVariables().get(0).getName()); //We set the class variable to be the last variable tan.setNameTarget(bn.getVariables().getListOfVariables() .get(bn.getVariables().getListOfVariables().size() - 1).getName()); Stopwatch watch = Stopwatch.createStarted(); //We just invoke this mode to learn the TAN model for the data stream BayesianNetwork model = tan.learn(data); System.out.println(watch.stop()); } }
From source file:com.sri.ai.praise.lang.translate.cli.RunTranslationsCLI.java
/** * Translate Probabilistic Models based on given command line arguments. * //from www . j a va 2 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:ninja.vertx.Benchmarker.java
static public void main(String[] args) throws Exception { // spin up standalone, but don't join Standalone standalone = new NinjaVertx() // Standalone standalone = new NinjaJetty() .externalConfigurationPath("conf/vertx.example.conf") .port(StandaloneHelper.findAvailablePort(8000, 9000)).start(); final int requests = 100000; final int threads = 1000; final OkHttpClient client = NinjaOkHttp3Tester.newHttpClientBuilder() .connectionPool(new ConnectionPool(threads, 60000L, TimeUnit.MILLISECONDS)).build(); final AtomicInteger requested = new AtomicInteger(); /**//from ww w .j ava2s . c om // get request w/ parameters final Request request = requestBuilder(standalone, "/parameters?a=joe&c=cat&d=dog&e=egg&f=frank&g=go") .header("Cookie", "TEST=THISISATESTCOOKIEHEADER") .build(); */ // json request w/ parameters byte[] json = "{ \"s\":\"string\", \"i\":2 }".getBytes(Charsets.UTF_8); final Request request = requestBuilder(standalone, "/benchmark_json?a=joe&c=cat&d=dog&e=egg&f=frank&g=go") .header("Cookie", "TEST=THISISATESTCOOKIEHEADER") .post(RequestBody.create(MediaType.parse("application/json"), json)).build(); /** final Request request = requestBuilder(standalone, "/benchmark_form?a=joe&c=cat&d=dog&e=egg&f=frank&g=go") .post(new FormBody.Builder() .add("a", "frank") .add("b", "2") .add("h", "hello") .add("z", "zulu") .build()) .build(); */ // warmup for (int i = 0; i < 100; i++) { Response response = executeRequest(client, request); response.body().close(); } final CountDownLatch startSignal = new CountDownLatch(1); final CountDownLatch doneSignal = new CountDownLatch(threads); ExecutorService threadPool = Executors.newFixedThreadPool(threads); for (int i = 0; i < threads; i++) { threadPool.submit(new Runnable() { @Override public void run() { try { startSignal.await(); while (requested.incrementAndGet() < requests) { Response response = executeRequest(client, request); response.body().close(); } doneSignal.countDown(); } catch (InterruptedException | IOException e) { log.error("", e); } } }); } // real Stopwatch stopwatch = Stopwatch.createStarted(); startSignal.countDown(); doneSignal.await(); stopwatch.stop(); log.info("Took {} ms for {} requests", stopwatch.elapsed(TimeUnit.MILLISECONDS), requests); logMemory(); standalone.shutdown(); threadPool.shutdown(); }
From source file:ninja.undertow.Benchmarker.java
static public void main(String[] args) throws Exception { // spin up standalone, but don't join Standalone standalone = new NinjaUndertow() //Standalone standalone = new NinjaJetty() .externalConfigurationPath("conf/undertow.example.conf") .port(StandaloneHelper.findAvailablePort(8000, 9000)).start(); final int requests = 100000; final int threads = 50; final OkHttpClient client = NinjaOkHttp3Tester.newHttpClientBuilder() .connectionPool(new ConnectionPool(threads, 60000L, TimeUnit.MILLISECONDS)).build(); final AtomicInteger requested = new AtomicInteger(); /**//from w w w. j ava 2 s . c om // get request w/ parameters final Request request = requestBuilder(standalone, "/parameters?a=joe&c=cat&d=dog&e=egg&f=frank&g=go") .header("Cookie", "TEST=THISISATESTCOOKIEHEADER") .build(); */ // json request w/ parameters byte[] json = "{ \"s\":\"string\", \"i\":2 }".getBytes(Charsets.UTF_8); final Request request = requestBuilder(standalone, "/benchmark_json?a=joe&c=cat&d=dog&e=egg&f=frank&g=go") .header("Cookie", "TEST=THISISATESTCOOKIEHEADER") .post(RequestBody.create(MediaType.parse("application/json"), json)).build(); /** final Request request = requestBuilder(standalone, "/benchmark_form?a=joe&c=cat&d=dog&e=egg&f=frank&g=go") .post(new FormBody.Builder() .add("a", "frank") .add("b", "2") .add("h", "hello") .add("z", "zulu") .build()) .build(); */ // warmup for (int i = 0; i < 100; i++) { Response response = executeRequest(client, request); response.body().close(); } final CountDownLatch startSignal = new CountDownLatch(1); final CountDownLatch doneSignal = new CountDownLatch(threads); ExecutorService threadPool = Executors.newFixedThreadPool(threads); for (int i = 0; i < threads; i++) { threadPool.submit(new Runnable() { @Override public void run() { try { startSignal.await(); while (requested.incrementAndGet() < requests) { Response response = executeRequest(client, request); response.body().close(); } doneSignal.countDown(); } catch (InterruptedException | IOException e) { log.error("", e); } } }); } // real Stopwatch stopwatch = Stopwatch.createStarted(); startSignal.countDown(); doneSignal.await(); stopwatch.stop(); log.info("Took {} ms for {} requests", stopwatch.elapsed(TimeUnit.MILLISECONDS), requests); logMemory(); standalone.shutdown(); threadPool.shutdown(); }
From source file:nl.knaw.huygens.timbuctoo.tools.importer.neww.CobwwwebRsImporter.java
public static void main(String[] args) throws Exception { Stopwatch stopWatch = Stopwatch.createStarted(); // Handle commandline arguments String directory = (args.length > 0) ? args[0] : "../../timbuctoo-testdata/src/main/resources/neww/"; CobwwwebRsImporter importer = null;/* w w w . ja va 2 s . c om*/ try { Injector injector = ToolsInjectionModule.createInjector(); Repository repository = injector.getInstance(Repository.class); IndexManager indexManager = injector.getInstance(IndexManager.class); importer = new CobwwwebRsImporter(repository, indexManager, directory); importer.importAll(); } finally { if (importer != null) { importer.close(); } LOG.info("Time used: {}", stopWatch); } }
From source file:com.google.devtools.build.android.GenerateRobolectricResourceSymbolsAction.java
public static void main(String[] args) throws Exception { final Stopwatch timer = Stopwatch.createStarted(); OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class, AaptConfigOptions.class); optionsParser.enableParamsFileSupport(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault())); optionsParser.parseAndExitUponError(args); AaptConfigOptions aaptConfigOptions = optionsParser.getOptions(AaptConfigOptions.class); Options options = optionsParser.getOptions(Options.class); try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("robolectric_resources_tmp")) { Path tmp = scopedTmp.getPath(); Path generatedSources = Files.createDirectories(tmp.resolve("generated_resources")); // The reported availableProcessors may be higher than the actual resources // (on a shared system). On the other hand, a lot of the work is I/O, so it's not completely // CPU bound. As a compromise, divide by 2 the reported availableProcessors. int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2); ListeningExecutorService executorService = MoreExecutors .listeningDecorator(Executors.newFixedThreadPool(numThreads)); try (Closeable closeable = ExecutorServiceCloser.createWith(executorService)) { logger.fine(String.format("Setup finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); final PlaceholderIdFieldInitializerBuilder robolectricIds = PlaceholderIdFieldInitializerBuilder .from(aaptConfigOptions.androidJar); ParsedAndroidData.loadedFrom(options.data, executorService, AndroidDataDeserializer.create()) .writeResourcesTo(new AndroidResourceSymbolSink() { @Override public void acceptSimpleResource(ResourceType type, String name) { robolectricIds.addSimpleResource(type, name); }/* ww w . ja v a2 s.co m*/ @Override public void acceptPublicResource(ResourceType type, String name, Optional<Integer> value) { robolectricIds.addPublicResource(type, name, value); } @Override public void acceptStyleableResource(FullyQualifiedName key, Map<FullyQualifiedName, Boolean> attrs) { robolectricIds.addStyleableResource(key, attrs); } }); final RClassGenerator generator = RClassGenerator.with(generatedSources, robolectricIds.build(), false); List<SymbolFileProvider> libraries = new ArrayList<>(); for (DependencyAndroidData dataDep : options.data) { SymbolFileProvider library = dataDep.asSymbolFileProvider(); libraries.add(library); } List<ListenableFuture<Boolean>> writeSymbolsTask = new ArrayList<>(); for (final Entry<String, Collection<ListenableFuture<ResourceSymbols>>> librarySymbolEntry : ResourceSymbols .loadFrom(libraries, executorService, null).asMap().entrySet()) { writeSymbolsTask .add(executorService.submit(new WriteLibraryRClass(librarySymbolEntry, generator))); } FailedFutureAggregator.forIOExceptionsWithMessage("Errors writing symbols.") .aggregateAndMaybeThrow(writeSymbolsTask); } logger.fine(String.format("Merging finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); AndroidResourceOutputs.createClassJar(generatedSources, options.classJarOutput); logger.fine(String.format("Create classJar finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); } catch (Exception e) { logger.log(Level.SEVERE, "Unexpected", e); throw e; } logger.fine(String.format("Resources merged in %sms", timer.elapsed(TimeUnit.MILLISECONDS))); }
From source file:nl.knaw.huygens.timbuctoo.tools.importer.dcar.DutchCaribbeanImporter.java
public static void main(String[] args) throws Exception { Stopwatch stopWatch = Stopwatch.createStarted(); // Handle commandline arguments String importDirName = (args.length > 0) ? args[0] : "../../AtlantischeGids/work/"; DutchCaribbeanImporter importer = null; try {/* w ww . j a v a2s . co m*/ Injector injector = ToolsInjectionModule.createInjector(); Repository repository = injector.getInstance(Repository.class); IndexManager indexManager = injector.getInstance(IndexManager.class); importer = new DutchCaribbeanImporter(repository, indexManager, importDirName); importer.importAll(); } finally { if (importer != null) { importer.close(); } LOG.info("Time used: {}", stopWatch); } }