Example usage for com.google.common.base Stopwatch stop

List of usage examples for com.google.common.base Stopwatch stop

Introduction

In this page you can find the example usage for com.google.common.base Stopwatch stop.

Prototype

public Stopwatch stop() 

Source Link

Document

Stops the stopwatch.

Usage

From source file:org.opendaylight.netconf.test.tool.client.http.perf.RestPerfClient.java

public static void main(String[] args) throws IOException {

    Parameters parameters = parseArgs(args, Parameters.getParser());
    parameters.validate();/*w  w  w  . ja va 2s .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, devicePort)));
        }
        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, devicePort)));
    }

    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");
    boolean allThreadsCompleted = true;
    final Stopwatch started = Stopwatch.createStarted();
    try {
        final List<Future<Void>> futures = executorService.invokeAll(callables, parameters.timeout,
                TimeUnit.MINUTES);
        for (int i = 0; i < futures.size(); i++) {
            Future<Void> future = futures.get(i);
            if (future.isCancelled()) {
                allThreadsCompleted = false;
                LOG.info("{}. thread timed out.", i + 1);
            } else {
                try {
                    future.get();
                } catch (final ExecutionException e) {
                    allThreadsCompleted = false;
                    LOG.info("{}. thread failed.", i + 1, e);
                }
            }
        }
    } catch (final InterruptedException e) {
        allThreadsCompleted = false;
        LOG.warn("Unable to execute requests", e);
    }
    executorService.shutdownNow();
    started.stop();

    LOG.info("FINISHED. Execution time: {}", started);
    // If some threads failed or timed out, skip calculation of requests per second value
    // and do not log it
    if (allThreadsCompleted) {
        LOG.info("Requests per second: {}",
                (parameters.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS)));
    }
    System.exit(0);
}

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;//www  .j av  a 2s  .  c  o  m
    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:org.cinchapi.concourse.shell.ConcourseShell.java

/**
 * Run the program.../*from  www. jav  a2s. c om*/
 * 
 * @param args - see {@link Options}
 * @throws IOException
 */
public static void main(String... args) throws IOException {
    ConsoleReader console = new ConsoleReader();
    console.setExpandEvents(false);
    Options opts = new Options();
    JCommander parser = new JCommander(opts, args);
    parser.setProgramName("concourse-shell");
    if (opts.help) {
        parser.usage();
        System.exit(1);
    }
    if (Strings.isNullOrEmpty(opts.password)) {
        opts.password = console.readLine("Password [" + opts.username + "]: ", '*');
    }
    try {
        Concourse concourse = Concourse.connect(opts.host, opts.port, opts.username, opts.password,
                opts.environment);

        final String env = concourse.getServerEnvironment();

        CommandLine.displayWelcomeBanner();
        Binding binding = new Binding();
        GroovyShell shell = new GroovyShell(binding);

        Stopwatch watch = Stopwatch.createUnstarted();
        console.println("Client Version " + Version.getVersion(ConcourseShell.class));
        console.println("Server Version " + concourse.getServerVersion());
        console.println("");
        console.println("Connected to the '" + env + "' environment.");
        console.println("");
        console.println("Type HELP for help.");
        console.println("Type EXIT to quit.");
        console.println("Use TAB for completion.");
        console.println("");
        console.setPrompt(MessageFormat.format("[{0}/cash]$ ", env));
        console.addCompleter(new StringsCompleter(getAccessibleApiMethodsUsingShortSyntax()));

        final List<String> methods = Lists.newArrayList(getAccessibleApiMethods());
        String line;
        while ((line = console.readLine().trim()) != null) {
            line = SyntaxTools.handleShortSyntax(line, methods);
            binding.setVariable("concourse", concourse);
            binding.setVariable("eq", Operator.EQUALS);
            binding.setVariable("ne", Operator.NOT_EQUALS);
            binding.setVariable("gt", Operator.GREATER_THAN);
            binding.setVariable("gte", Operator.GREATER_THAN_OR_EQUALS);
            binding.setVariable("lt", Operator.LESS_THAN);
            binding.setVariable("lte", Operator.LESS_THAN_OR_EQUALS);
            binding.setVariable("bw", Operator.BETWEEN);
            binding.setVariable("regex", Operator.REGEX);
            binding.setVariable("nregex", Operator.NOT_REGEX);
            binding.setVariable("lnk2", Operator.LINKS_TO);
            binding.setVariable("date", STRING_TO_TIME);
            binding.setVariable("time", STRING_TO_TIME);
            binding.setVariable("where", WHERE);
            binding.setVariable("tag", STRING_TO_TAG);
            if (line.equalsIgnoreCase("exit")) {
                concourse.exit();
                System.exit(0);
            } else if (line.equalsIgnoreCase("help") || line.equalsIgnoreCase("man")) {
                Process p = Runtime.getRuntime()
                        .exec(new String[] { "sh", "-c", "echo \"" + HELP_TEXT + "\" | less > /dev/tty" });
                p.waitFor();
            } else if (containsBannedCharSequence(line)) {
                System.err.println(
                        "Cannot complete command because " + "it contains an illegal character sequence.");
            } else if (Strings.isNullOrEmpty(line)) { // CON-170
                continue;
            } else {
                watch.reset().start();
                Object value = null;
                try {
                    value = shell.evaluate(line, "ConcourseShell");
                    watch.stop();
                    if (value != null) {
                        System.out.println(
                                "Returned '" + value + "' in " + watch.elapsed(TimeUnit.MILLISECONDS) + " ms");
                    } else {
                        System.out.println("Completed in " + watch.elapsed(TimeUnit.MILLISECONDS) + " ms");
                    }
                } catch (Exception e) {
                    if (e.getCause() instanceof TTransportException) {
                        die(e.getMessage());
                    } else if (e.getCause() instanceof TSecurityException) {
                        die("A security change has occurred and your " + "session cannot continue");
                    } else {
                        System.err.print("ERROR: " + e.getMessage());
                    }
                }

            }
            System.out.print("\n");
        }
    } catch (Exception e) {
        if (e.getCause() instanceof TTransportException) {
            die("Unable to connect to " + opts.username + "@" + opts.host + ":" + opts.port
                    + " with the specified password");
        } else if (e.getCause() instanceof TSecurityException) {
            die("Invalid username/password combination.");
        } else {
            die(e.getMessage());
        }
    } finally {
        try {
            TerminalFactory.get().restore();
        } catch (Exception e) {
            die(e.getMessage());
        }
    }

}

From source file:com.paolodragone.wsn.disambiguation.WsnDisambiguator.java

public static void main(String[] args) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    try {/*from  ww w . j a  v  a2s .c  om*/
        System.out.println("Loading...");

        // Readers
        WsnConfiguration configuration = WsnConfiguration.getInstance();
        Reader sensesFileReader = Files.newBufferedReader(configuration.getSensesFilePath());
        Reader synonymsFileReader = Files.newBufferedReader(configuration.getSynonymsFilePath());
        Reader sensesSynonymsFileReader = Files.newBufferedReader(configuration.getSensesSynonymsFilePath());
        Reader termsFileReader = Files.newBufferedReader(configuration.getTermsFilePath());
        Reader termWeightsFileReader = Files.newBufferedReader(configuration.getTermWeightsFilePath());

        // Get sense Stream
        SensesDataSet sensesDataSet = new SensesDataSet();
        SensesDataSet sensesDataSetView;
        sensesDataSetView = sensesDataSet.getView(sensesDataSet.excludeColumns(SenseColumn.Gloss));
        Stream<Sense> senseStream = sensesDataSetView.getEntityStream(sensesFileReader).parallel();
        senseStream = Senses.filterValidSenses(senseStream);
        Collection<Sense> senses = DStreamSupport.toList(senseStream);
        Map<Integer, Sense> senseMap = DCollections.collectionToMap(senses, Sense::getId, new HashMap<>());

        // Set terms
        TermsDataSet termsDataSet = new TermsDataSet();
        TermsDataSet termsDataSetView;
        termsDataSetView = termsDataSet.getView(termsDataSet.excludeColumns(TermsDataSet.TermColumn.Word));
        Stream<Term> termStream = Terms.filterValidTerms(termsDataSetView.getEntityStream(termsFileReader));
        TermsDataSet.setTerms(senseMap, termStream);

        // Set synonyms
        SynonymsDataSet synonymsDataSet = new SynonymsDataSet();
        Collection<Synonym> synonyms = DStreamSupport
                .toList(synonymsDataSet.getEntityStream(synonymsFileReader));
        Map<Integer, Synonym> synonymMap = SynonymsDataSet.getSynonymMap(synonyms);
        SensesSynonymsDataSet sensesSynonymsDataSet = new SensesSynonymsDataSet();
        Stream<SenseSynonym> senseSynonymStream = sensesSynonymsDataSet
                .getEntityStream(sensesSynonymsFileReader);
        SensesSynonymsDataSet.setSynonyms(senseMap, synonymMap, senseSynonymStream);
        synonyms = null;
        synonymMap = null;

        // Get term weights
        TermWeightsDataSet termWeightsDataSet = new TermWeightsDataSet();
        Stream<TermWeight> termWeightStream = termWeightsDataSet.getEntityStream(termWeightsFileReader);
        Map<String, Double> termWeightMap = TermWeightsDataSet.getTermWeightMap(termWeightStream);

        System.out.println("Done.");

        WsnDisambiguator disambiguator = new WsnDisambiguator(senses, termWeightMap, defaultContextDepth);
        termWeightMap = null;

        DisambiguatedTermsPrinter disambiguatedTermsPrinter = new DisambiguatedTermsPrinter();
        disambiguator.epochEvent.addEventHandler(disambiguatedTermsPrinter::printEpoch);
        disambiguator.seenTermEvent.addEventHandler(disambiguatedTermsPrinter::incrementTerms);
        disambiguator.disambiguatedTermEvent
                .addEventHandler(disambiguatedTermsPrinter::incrementDisambiguatedTerms);
        disambiguator.changedEvent.addEventHandler(disambiguatedTermsPrinter::changed);

        /*
                    CountResult countResult = disambiguator.countTerms();
                    System.out.println("Total terms: " + countResult.getTotalTerms());
                    System.out.println("Valid terms: " + countResult.getValidTerms());
                    System.out.println("Unsolved terms: " + countResult.getUnsolvedTerms());
                    System.out.println("Monosemous terms: " + countResult.getMonosemousTerms());
                    System.out.println("Ambiguous terms: " + countResult.getAmbiguousTerms());
        */

        List<SemanticEdge> semanticNetwork = disambiguator.buildSemanticNetwork();
        Writer semanticNetworkFileWriter = Files.newBufferedWriter(configuration.getSemanticNetworkFilePath());

        SemanticNetworkDataSet semanticNetworkDataSet = new SemanticNetworkDataSet();
        semanticNetworkDataSet.writeEntities(semanticNetwork.stream(), semanticNetworkFileWriter);

    } catch (Exception e) {
        e.printStackTrace();
    }
    long elapsed = stopwatch.stop().elapsed(TimeUnit.MINUTES);
    System.out.println("\nTotal time: " + elapsed + " min");
}

From source file:ezbake.data.common.LoggingUtils.java

public static void stopAndLogStopWatch(Logger logger, Stopwatch watch, String name) {
    watch.stop();
    logger.info("{}|{} miliseconds", name, watch.elapsed(TimeUnit.MILLISECONDS));
}

From source file:ch.oakmountain.tpa.solver.TPAUtil.java

public static void stopStopWatch(Stopwatch stopwatch, String message) {
    stopwatch.stop();
    long secsBuildModel = stopwatch.elapsed(TimeUnit.MILLISECONDS);
    LOGGER.info("TIME TO " + message + ": " + stopwatch);
}

From source file:ezbake.data.common.LoggingUtils.java

public static void logResetAndStartStopWatch(Logger logger, Stopwatch watch, String name) {
    watch.stop();
    logger.info("{}|{} miliseconds", name, watch.elapsed(TimeUnit.MILLISECONDS));
    watch.reset();/*www  .ja  v a2  s  .  co  m*/
    watch.start();
}

From source file:com.github.zhongl.util.Benchmarks.java

public static void benchmark(String name, Runnable runnable, int times) {
    Stopwatch stopwatch = new Stopwatch().start();
    runnable.run();/*from   w w  w  .j  a v a2s .  co m*/
    stopwatch.stop();

    long latency = stopwatch.elapsedTime(TimeUnit.NANOSECONDS) / times;
    double tps = times * 1.0 / stopwatch.elapsedTime(TimeUnit.MILLISECONDS) * 1000;

    System.out.println(format("{0} : elpase[{1}], latency[{2, number}ns], TPS[{3, number,#.##}]", name,
            stopwatch, latency, tps));
}

From source file:com.mysema.testutil.Runner.java

public static void run(String label, Benchmark benchmark) throws Exception {
    // warmup//from   w  ww . j a v  a  2s.  c  o m
    benchmark.run(WARMUP);
    System.err.print("- ");

    // run garbage collection
    System.gc();
    System.err.print("- ");

    // perform timing
    Stopwatch stopwatch = Stopwatch.createStarted();
    benchmark.run(BENCHMARK);
    System.err.println(label + " " + stopwatch.stop().toString());
}

From source file:org.eclipse.viatra.dse.monitor.PerformanceMonitorManager.java

public static void endTimer(String name) {
    Stopwatch stopwatch = timers.get(name + Thread.currentThread().getId());
    if (stopwatch != null) {
        stopwatch.stop();
        addMeasurementToTimer(stopwatch.elapsedTime(TimeUnit.NANOSECONDS), name);
    }/*from  w w  w. jav a2 s .c o  m*/
}