List of usage examples for com.google.common.base Stopwatch stop
public Stopwatch stop()
From source file:org.opendaylight.controller.netconf.test.tool.client.http.perf.RestPerfClient.java
public static void main(String[] args) throws IOException { Parameters parameters = parseArgs(args, Parameters.getParser()); parameters.validate();/*from www. jav a 2 s . c o m*/ throttle = parameters.throttle / parameters.threadAmount; if (parameters.async && parameters.threadAmount > 1) { LOG.info("Throttling per thread: {}", throttle); } final String editContentString; try { editContentString = Files.toString(parameters.editContent, Charsets.UTF_8); } catch (final IOException e) { throw new IllegalArgumentException("Cannot read content of " + parameters.editContent); } final int threadAmount = parameters.threadAmount; LOG.info("thread amount: {}", threadAmount); final int requestsPerThread = parameters.editCount / parameters.threadAmount; LOG.info("requestsPerThread: {}", requestsPerThread); final int leftoverRequests = parameters.editCount % parameters.threadAmount; LOG.info("leftoverRequests: {}", leftoverRequests); final ArrayList<ArrayList<DestToPayload>> allThreadsPayloads = new ArrayList<>(); for (int i = 0; i < threadAmount; i++) { final ArrayList<DestToPayload> payloads = new ArrayList<>(); for (int j = 0; j < requestsPerThread; j++) { final int devicePort = parameters.sameDevice ? parameters.devicePortRangeStart : parameters.devicePortRangeStart + i; final StringBuilder destBuilder = new StringBuilder(dest); destBuilder.replace(destBuilder.indexOf(HOST_KEY), destBuilder.indexOf(HOST_KEY) + HOST_KEY.length(), parameters.ip) .replace(destBuilder.indexOf(PORT_KEY), destBuilder.indexOf(PORT_KEY) + PORT_KEY.length(), parameters.port + ""); final StringBuilder suffixBuilder = new StringBuilder(parameters.destination); if (suffixBuilder.indexOf(DEVICE_PORT_KEY) != -1) { suffixBuilder.replace(suffixBuilder.indexOf(DEVICE_PORT_KEY), suffixBuilder.indexOf(DEVICE_PORT_KEY) + DEVICE_PORT_KEY.length(), devicePort + ""); } destBuilder.append(suffixBuilder); payloads.add(new DestToPayload(destBuilder.toString(), prepareMessage(i, j, editContentString))); } allThreadsPayloads.add(payloads); } for (int i = 0; i < leftoverRequests; i++) { ArrayList<DestToPayload> payloads = allThreadsPayloads.get(allThreadsPayloads.size() - 1); final int devicePort = parameters.sameDevice ? parameters.devicePortRangeStart : parameters.devicePortRangeStart + threadAmount - 1; final StringBuilder destBuilder = new StringBuilder(dest); destBuilder.replace(destBuilder.indexOf(HOST_KEY), destBuilder.indexOf(HOST_KEY) + HOST_KEY.length(), parameters.ip).replace(destBuilder.indexOf(PORT_KEY), destBuilder.indexOf(PORT_KEY) + PORT_KEY.length(), parameters.port + ""); final StringBuilder suffixBuilder = new StringBuilder(parameters.destination); if (suffixBuilder.indexOf(DEVICE_PORT_KEY) != -1) { suffixBuilder.replace(suffixBuilder.indexOf(DEVICE_PORT_KEY), suffixBuilder.indexOf(DEVICE_PORT_KEY) + DEVICE_PORT_KEY.length(), devicePort + ""); } destBuilder.append(suffixBuilder); payloads.add(new DestToPayload(destBuilder.toString(), prepareMessage(threadAmount - 1, requestsPerThread + i, editContentString))); } final ArrayList<PerfClientCallable> callables = new ArrayList<>(); for (ArrayList<DestToPayload> payloads : allThreadsPayloads) { callables.add(new PerfClientCallable(parameters, payloads)); } final ExecutorService executorService = Executors.newFixedThreadPool(threadAmount); LOG.info("Starting performance test"); final Stopwatch started = Stopwatch.createStarted(); try { final List<Future<Void>> futures = executorService.invokeAll(callables, 5, TimeUnit.MINUTES); for (final Future<Void> future : futures) { try { future.get(4L, TimeUnit.MINUTES); } catch (ExecutionException | TimeoutException e) { throw new RuntimeException(e); } } executorService.shutdownNow(); } catch (final InterruptedException e) { throw new RuntimeException("Unable to execute requests", e); } started.stop(); LOG.info("FINISHED. Execution time: {}", started); LOG.info("Requests per second: {}", (parameters.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS))); System.exit(0); }
From source file:com.sri.ai.praise.lang.translate.cli.RunTranslationsCLI.java
/** * Translate Probabilistic Models based on given command line arguments. * /*w ww.j a va 2s . 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:org.opendaylight.netconf.test.tool.client.stress.StressClient.java
public static void main(final String[] args) { params = parseArgs(args, Parameters.getParser()); params.validate();// ww w . j a v a2 s . c om final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(Logger.ROOT_LOGGER_NAME); root.setLevel(params.debug ? Level.DEBUG : Level.INFO); final int threadAmount = params.threadAmount; LOG.info("thread amount: " + threadAmount); final int requestsPerThread = params.editCount / params.threadAmount; LOG.info("requestsPerThread: " + requestsPerThread); final int leftoverRequests = params.editCount % params.threadAmount; LOG.info("leftoverRequests: " + leftoverRequests); LOG.info("Preparing messages"); // Prepare all msgs up front final List<List<NetconfMessage>> allPreparedMessages = new ArrayList<>(threadAmount); for (int i = 0; i < threadAmount; i++) { if (i != threadAmount - 1) { allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread)); } else { allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread + leftoverRequests)); } } final String editContentString; try { editContentString = Files.toString(params.editContent, Charsets.UTF_8); } catch (final IOException e) { throw new IllegalArgumentException("Cannot read content of " + params.editContent); } for (int i = 0; i < threadAmount; i++) { final List<NetconfMessage> preparedMessages = allPreparedMessages.get(i); int padding = 0; if (i == threadAmount - 1) { padding = leftoverRequests; } for (int j = 0; j < requestsPerThread + padding; j++) { LOG.debug("id: " + (i * requestsPerThread + j)); preparedMessages.add(prepareMessage(i * requestsPerThread + j, editContentString)); } } final NioEventLoopGroup nioGroup = new NioEventLoopGroup(); final Timer timer = new HashedWheelTimer(); final NetconfClientDispatcherImpl netconfClientDispatcher = configureClientDispatcher(params, nioGroup, timer); final List<StressClientCallable> callables = new ArrayList<>(threadAmount); for (final List<NetconfMessage> messages : allPreparedMessages) { callables.add(new StressClientCallable(params, netconfClientDispatcher, messages)); } final ExecutorService executorService = Executors.newFixedThreadPool(threadAmount); LOG.info("Starting stress test"); final Stopwatch started = Stopwatch.createStarted(); try { final List<Future<Boolean>> futures = executorService.invokeAll(callables); for (final Future<Boolean> future : futures) { try { future.get(4L, TimeUnit.MINUTES); } catch (ExecutionException | TimeoutException e) { throw new RuntimeException(e); } } executorService.shutdownNow(); } catch (final InterruptedException e) { throw new RuntimeException("Unable to execute requests", e); } started.stop(); LOG.info("FINISHED. Execution time: {}", started); LOG.info("Requests per second: {}", (params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS))); // Cleanup timer.stop(); try { nioGroup.shutdownGracefully().get(20L, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { LOG.warn("Unable to close executor properly", e); } //stop the underlying ssh thread that gets spawned if we use ssh if (params.ssh) { AsyncSshHandler.DEFAULT_CLIENT.stop(); } }
From source file:org.opendaylight.controller.netconf.test.tool.client.stress.StressClient.java
public static void main(final String[] args) { final Parameters params = parseArgs(args, Parameters.getParser()); params.validate();// ww w .ja v a2s.c o m final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(Logger.ROOT_LOGGER_NAME); root.setLevel(params.debug ? Level.DEBUG : Level.INFO); final int threadAmount = params.threadAmount; LOG.info("thread amount: " + threadAmount); final int requestsPerThread = params.editCount / params.threadAmount; LOG.info("requestsPerThread: " + requestsPerThread); final int leftoverRequests = params.editCount % params.threadAmount; LOG.info("leftoverRequests: " + leftoverRequests); LOG.info("Preparing messages"); // Prepare all msgs up front final List<List<NetconfMessage>> allPreparedMessages = new ArrayList<>(threadAmount); for (int i = 0; i < threadAmount; i++) { if (i != threadAmount - 1) { allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread)); } else { allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread + leftoverRequests)); } } final String editContentString; try { editContentString = Files.toString(params.editContent, Charsets.UTF_8); } catch (final IOException e) { throw new IllegalArgumentException("Cannot read content of " + params.editContent); } for (int i = 0; i < threadAmount; i++) { final List<NetconfMessage> preparedMessages = allPreparedMessages.get(i); int padding = 0; if (i == threadAmount - 1) { padding = leftoverRequests; } for (int j = 0; j < requestsPerThread + padding; j++) { LOG.debug("id: " + (i * requestsPerThread + j)); preparedMessages.add(prepareMessage(i * requestsPerThread + j, editContentString)); } } final NioEventLoopGroup nioGroup = new NioEventLoopGroup(); final Timer timer = new HashedWheelTimer(); final NetconfClientDispatcherImpl netconfClientDispatcher = configureClientDispatcher(params, nioGroup, timer); final List<StressClientCallable> callables = new ArrayList<>(threadAmount); for (final List<NetconfMessage> messages : allPreparedMessages) { callables.add(new StressClientCallable(params, netconfClientDispatcher, messages)); } final ExecutorService executorService = Executors.newFixedThreadPool(threadAmount); LOG.info("Starting stress test"); final Stopwatch started = Stopwatch.createStarted(); try { final List<Future<Boolean>> futures = executorService.invokeAll(callables); for (final Future<Boolean> future : futures) { try { future.get(4L, TimeUnit.MINUTES); } catch (ExecutionException | TimeoutException e) { throw new RuntimeException(e); } } executorService.shutdownNow(); } catch (final InterruptedException e) { throw new RuntimeException("Unable to execute requests", e); } started.stop(); LOG.info("FINISHED. Execution time: {}", started); LOG.info("Requests per second: {}", (params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS))); // Cleanup timer.stop(); try { nioGroup.shutdownGracefully().get(20L, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { LOG.warn("Unable to close executor properly", e); } //stop the underlying ssh thread that gets spawned if we use ssh if (params.ssh) { AsyncSshHandler.DEFAULT_CLIENT.stop(); } }
From source file:com.mgmtp.perfload.perfalyzer.PerfAlyzer.java
public static void main(final String[] args) { JCommander jCmd = null;//from w ww . j a v a2 s. com try { Stopwatch stopwatch = Stopwatch.createStarted(); LOG.info("Starting perfAlyzer..."); LOG.info("Arguments:"); for (String arg : args) { LOG.info(arg); } PerfAlyzerArgs perfAlyzerArgs = new PerfAlyzerArgs(); jCmd = new JCommander(perfAlyzerArgs); jCmd.parse(args); Injector injector = Guice.createInjector(new PerfAlyzerModule(perfAlyzerArgs)); PerfAlyzer perfAlyzer = injector.getInstance(PerfAlyzer.class); perfAlyzer.runPerfAlyzer(); ExecutorService executorService = injector.getInstance(ExecutorService.class); executorService.shutdownNow(); stopwatch.stop(); LOG.info("Done."); LOG.info("Total execution time: {}", stopwatch); } catch (ParameterException ex) { LOG.error(ex.getMessage()); StringBuilder sb = new StringBuilder(200); jCmd.usage(sb); LOG.info(sb.toString()); System.exit(1); } catch (Exception ex) { LOG.error(ex.getMessage(), ex); System.exit(1); } }
From source file:org.opendaylight.netconf.test.tool.Main.java
public static void main(final String[] args) { final TesttoolParameters params = TesttoolParameters.parseArgs(args, TesttoolParameters.getParser()); params.validate();/*from w w w. j a va 2s. co m*/ final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(Logger.ROOT_LOGGER_NAME); root.setLevel(params.debug ? Level.DEBUG : Level.INFO); final NetconfDeviceSimulator netconfDeviceSimulator = new NetconfDeviceSimulator(params.threadPoolSize); try { LOG.debug("Trying to start netconf test-tool with parameters {}", params); final List<Integer> openDevices = netconfDeviceSimulator.start(params); if (openDevices.size() == 0) { LOG.error("Failed to start any simulated devices, exiting..."); System.exit(1); } if (params.controllerDestination != null) { final ArrayList<ArrayList<Execution.DestToPayload>> allThreadsPayloads = params .getThreadsPayloads(openDevices); final ArrayList<Execution> executions = new ArrayList<>(); for (ArrayList<Execution.DestToPayload> payloads : allThreadsPayloads) { executions.add(new Execution(params, payloads)); } final ExecutorService executorService = Executors.newFixedThreadPool(params.threadAmount); final Stopwatch time = Stopwatch.createStarted(); List<Future<Void>> futures = executorService.invokeAll(executions, params.timeOut, TimeUnit.SECONDS); int threadNum = 0; for (Future<Void> future : futures) { threadNum++; if (future.isCancelled()) { LOG.info("{}. thread timed out.", threadNum); } else { try { future.get(); } catch (final ExecutionException e) { LOG.info("{}. thread failed.", threadNum, e); } } } time.stop(); LOG.info("Time spent with configuration of devices: {}.", time); } if (params.distroFolder != null) { final ConfigGenerator configGenerator = new ConfigGenerator(params.distroFolder, openDevices); final List<File> generated = configGenerator.generate(params.ssh, params.generateConfigBatchSize, params.generateConfigsTimeout, params.generateConfigsAddress, params.devicesPerPort); configGenerator.updateFeatureFile(generated); configGenerator.changeLoadOrder(); } } catch (final Exception e) { LOG.error("Unhandled exception", e); netconfDeviceSimulator.close(); System.exit(1); } // Block main thread synchronized (netconfDeviceSimulator) { try { netconfDeviceSimulator.wait(); } catch (final InterruptedException e) { throw new RuntimeException(e); } } }
From source file:nl.knaw.huygens.timbuctoo.tools.conversion.MongoTinkerPopConverter.java
public static void main(String[] args) throws Exception { Stopwatch stopwatch = Stopwatch.createStarted(); Injector injector = ToolsInjectionModule.createInjectorWithoutSolr(); Graph graph = injector.getInstance(Graph.class); ElementConverterFactory converterFactory = injector.getInstance(ElementConverterFactory.class); IdGenerator idGenerator = injector.getInstance(IdGenerator.class); TinkerPopConversionStorage graphStorage = injector.getInstance(TinkerPopConversionStorage.class); MongoConversionStorage mongoStorage = injector.getInstance(MongoConversionStorage.class); TypeRegistry registry = injector.getInstance(TypeRegistry.class); MongoTinkerPopConverter converter = new MongoTinkerPopConverter(graphStorage, graph, idGenerator, converterFactory, registry, mongoStorage); try {/* w w w . ja va 2 s . c o m*/ converter.convertSystemEntities(); converter.convertDomainEntities(); } finally { graph.shutdown(); mongoStorage.close(); } LOG.info("Done in {}", stopwatch.stop()); }
From source file:eu.amidst.dynamic.utils.DynamicBayesianNetworkSampler.java
public static void main(String[] args) throws Exception { Stopwatch watch = Stopwatch.createStarted(); DynamicBayesianNetworkGenerator dbnGenerator = new DynamicBayesianNetworkGenerator(); dbnGenerator.setNumberOfContinuousVars(0); dbnGenerator.setNumberOfDiscreteVars(3); dbnGenerator.setNumberOfStates(2);//from www.j a v a2 s . c o m DynamicBayesianNetwork network = DynamicBayesianNetworkGenerator.generateDynamicNaiveBayes(new Random(0), 2, true); DynamicBayesianNetworkSampler sampler = new DynamicBayesianNetworkSampler(network); sampler.setSeed(0); DataStream<DynamicDataInstance> dataStream = sampler.sampleToDataBase(3, 2); DataStreamWriter.writeDataToFile(dataStream, "./datasets/simulated/dnb-samples.arff"); System.out.println(watch.stop()); for (DynamicAssignment dynamicdataassignment : sampler.sampleToDataBase(3, 2)) { System.out.println("\n Sequence ID" + dynamicdataassignment.getSequenceID()); System.out.println("\n Time ID" + dynamicdataassignment.getTimeID()); System.out.println(dynamicdataassignment.outputString()); } }
From source file:com.paolodragone.wsn.extraction.SenseExtractor.java
public static void main(String[] args) { Stopwatch stopwatch = Stopwatch.createStarted(); try {/*from w ww . j a v a 2 s . c o m*/ WsnConfiguration configuration = WsnConfiguration.getInstance(); Path wiktionaryDumpFilePath = configuration.getWiktionaryDumpFilePath(); Path sensesFilePath = configuration.getSensesFilePath(); SenseExtractor extractor = new SenseExtractor(); SenseCountPrinter senseCountPrinter = new SenseCountPrinter(extractor); Timer senseCountPrinterTimer = new Timer("SenseCountPrinter", true); senseCountPrinterTimer.scheduleAtFixedRate(senseCountPrinter, 0, 1000); Reader wiktionaryDumpFileReader = Files.newBufferedReader(wiktionaryDumpFilePath); Stream<Sense> senseStream = extractor.extractSenses(wiktionaryDumpFileReader); SensesDataSet sensesDataSet = new SensesDataSet(); Writer sensesFileWriter = Files.newBufferedWriter(sensesFilePath); sensesDataSet.writeEntities(senseStream, sensesFileWriter); } catch (Exception e) { e.printStackTrace(); } long elapsed = stopwatch.stop().elapsed(TimeUnit.MINUTES); System.out.println("\nTotal time: " + elapsed + " min"); }
From source file:com.inferapp.DiscoverySource.java
public static void main(String[] args) { try {//from w w w. j a va 2 s.c om Stopwatch timer = Stopwatch.createStarted(); deleteFilesInFolder(new File("s:\\results\\")); loadDiscoveryRules(); loadDiscoverySignatures(); processAllScans(); saveDiscoveryAggregateResults(); saveDiscoveryAggregateSources(); logExecutionTime("Total (Java): " + timer.stop().elapsed(TimeUnit.SECONDS) + "\r\n"); } catch (IOException ex) { System.out.println(ex.toString()); System.exit(1); } }