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

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

Introduction

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

Prototype

@CheckReturnValue
public long elapsed(TimeUnit desiredUnit) 

Source Link

Document

Returns the current elapsed time shown on this stopwatch, expressed in the desired time unit, with any fraction rounded down.

Usage

From source file:com.couchbase.roadrunner.RoadRunner.java

/**
 * Initialize the RoadRunner.//from   www .j a va  2 s  .co  m
 *
 * This method is responsible for parsing the passed in command line arguments
 * and also dispatch the bootstrapping of the actual workload runner.
 *
 * @param args Command line arguments to be passed in.
 */
public static void main(final String[] args) {
    CommandLine params = null;
    try {
        params = parseCommandLine(args);
    } catch (ParseException ex) {
        LOGGER.error("Exception while parsing command line!", ex);
        System.exit(-1);
    }

    if (params.hasOption(OPT_HELP)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("roadrunner", getCommandLineOptions());
        System.exit(0);
    }

    GlobalConfig config = GlobalConfig.fromCommandLine(params);
    WorkloadDispatcher dispatcher = new WorkloadDispatcher(config);

    LOGGER.info("Running with Config: " + config.toString());

    try {
        LOGGER.debug("Initializing ClientHandlers.");
        dispatcher.init();
    } catch (Exception ex) {
        LOGGER.error("Error while initializing the ClientHandlers: ", ex);
        System.exit(-1);
    }

    Stopwatch workloadStopwatch = new Stopwatch().start();
    try {
        LOGGER.info("Running Workload.");
        dispatcher.dispatchWorkload();
    } catch (Exception ex) {
        LOGGER.error("Error while running the Workload: ", ex);
        System.exit(-1);
    }
    workloadStopwatch.stop();

    LOGGER.debug("Finished Workload.");

    LOGGER.info("==== RESULTS ====");

    dispatcher.prepareMeasures();

    long totalOps = dispatcher.getTotalOps();
    long measuredOps = dispatcher.getMeasuredOps();

    LOGGER.info("Operations: measured " + measuredOps + "ops out of total " + totalOps + "ops.");

    Map<String, List<Stopwatch>> measures = dispatcher.getMeasures();
    for (Map.Entry<String, List<Stopwatch>> entry : measures.entrySet()) {
        Histogram h = new Histogram(60 * 60 * 1000, 5);
        for (Stopwatch watch : entry.getValue()) {
            h.recordValue(watch.elapsed(TimeUnit.MICROSECONDS));
        }

        LOGGER.info("Percentile (microseconds) for \"" + entry.getKey() + "\" Workload:");
        LOGGER.info("   50%:" + (Math.round(h.getValueAtPercentile(0.5) * 100) / 100) + "   75%:"
                + (Math.round(h.getValueAtPercentile(0.75) * 100) / 100) + "   95%:"
                + (Math.round(h.getValueAtPercentile(0.95) * 100) / 100) + "   99%:"
                + (Math.round(h.getValueAtPercentile(0.99) * 100) / 100));
    }

    LOGGER.info("Elapsed: " + workloadStopwatch.elapsed(TimeUnit.MILLISECONDS) + "ms");

    List<Stopwatch> elapsedThreads = dispatcher.getThreadElapsed();
    long shortestThread = 0;
    long longestThread = 0;
    for (Stopwatch threadWatch : elapsedThreads) {
        long threadMs = threadWatch.elapsed(TimeUnit.MILLISECONDS);
        if (longestThread == 0 || threadMs > longestThread) {
            longestThread = threadMs;
        }
        if (shortestThread == 0 || threadMs < shortestThread) {
            shortestThread = threadMs;
        }
    }

    LOGGER.info("Shortest Thread: " + shortestThread + "ms");
    LOGGER.info("Longest Thread: " + longestThread + "ms");

}

From source file:org.glowroot.local.store.TraceDaoPerformanceMain.java

public static void main(String... args) throws Exception {
    DataSource dataSource = new DataSource();
    CappedDatabase cappedDatabase = new CappedDatabase(new File("glowroot.capped.db"), 1000000);
    TraceDao traceDao = new TraceDao(dataSource, cappedDatabase);

    Stopwatch stopwatch = Stopwatch.createStarted();
    for (int i = 0; i < 1000; i++) {
        Trace trace = TraceTestData.createTrace();
        CharSource entries = TraceTestData.createEntries();
        traceDao.store(trace, entries, null);
    }/*  w  w w  .j  a  v a2 s . c om*/
    logger.info("elapsed time: {}", stopwatch.elapsed(MILLISECONDS));
    logger.info("num traces: {}", traceDao.count());
}

From source file:com.jejking.hh.nord.gazetteer.osm.streets.MapStreetsToPolygons.java

/**
 * Maps the extracted streets to the lowest level administrative districts, the "Ortsteile", numbered districted.
 * /*from w  w  w.  j  av  a 2s .  co  m*/
 * @param args
 *            directory in which the Neo4j database exists.
 */
public static void main(String[] args) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    GraphDatabaseService graph = new GraphDatabaseFactory().newEmbeddedDatabase(args[0]);
    registerShutdownHook(graph);

    MapStreetsToPolygons.mapStreetsToAdminPolygons(graph);
    System.out.println(
            "Linked streets to polygons. Elapsed time: " + stopwatch.elapsed(TimeUnit.SECONDS) + " seconds");

}

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  w  w w.  j a  va  2s .c  o  m
    // 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();

    /**/* w  w  w .j  a v a2s.com*/
    // 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:eu.amidst.core.inference.messagepassing.VMP.java

public static void main(String[] arguments) throws IOException, ClassNotFoundException {

    BayesianNetwork bn = BayesianNetworkLoader.loadFromFile("./networks/dataWeka/Munin1.bn");
    System.out.println(bn.getNumberOfVars());
    System.out.println(bn.getDAG().getNumberOfLinks());
    System.out.println(bn.getConditionalDistributions().stream().mapToInt(p -> p.getNumberOfParameters()).max()
            .getAsInt());//  w  ww. j a v a 2s  . c o  m

    VMP vmp = new VMP();
    InferenceEngine.setInferenceAlgorithm(vmp);
    Variable var = bn.getVariables().getVariableById(0);
    UnivariateDistribution uni = null;
    double avg = 0;
    for (int i = 0; i < 20; i++) {
        Stopwatch watch = Stopwatch.createStarted();
        uni = InferenceEngine.getPosterior(var, bn);
        System.out.println(watch.stop());
        avg += watch.elapsed(TimeUnit.MILLISECONDS);
    }
    System.out.println(avg / 20);
    System.out.println(uni);

}

From source file:com.jejking.hh.nord.gazetteer.opendata.CreatePartialGazetteerWithOpenData.java

/**
 * Main method.//from  w  ww.  j  av  a2  s  .  com
 * 
 * @param args
 *            , first arg is path to directory in which to create/open a Neo4j database with the gazetteer.
 */
public static void main(String[] args) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    GraphDatabaseService graph = new GraphDatabaseFactory().newEmbeddedDatabase(args[0]);
    registerShutdownHook(graph);

    // we want an additional index on adminstrative area - name
    setupSchema(graph);
    System.out.println("Setup indexes. Elapsed time: " + stopwatch.elapsed(TimeUnit.SECONDS) + " seconds");

    CreatePartialGazetteerWithOpenData.writeHamburgPolygons(graph);
    System.out.println(
            "Wrote hamburg polygons. Elapsed time: " + stopwatch.elapsed(TimeUnit.SECONDS) + " seconds");
}

From source file:com.jejking.hh.nord.gazetteer.osm.streets.WriteStreets.java

/**
 * Imports an extract from Open Street Map into Neo4j.
 * /*from   ww w. jav  a  2 s. co m*/
 * @param args
 *            directory in which the Neo4j database exists.
 */
public static void main(String[] args) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
    GraphDatabaseService graph = new GraphDatabaseFactory().newEmbeddedDatabase(args[0]);
    registerShutdownHook(graph);

    WriteStreets.writeStreets(geometryFactory, graph);
    System.out.println("Wrote streets. Elapsed time: " + stopwatch.elapsed(TimeUnit.SECONDS) + " seconds");

}

From source file:ch.petikoch.examples.rxjava.backup_requests.WordCountWithBackupRequests.java

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

    int numberOfSentences = 5_000;

    System.out.println("-----------------------------------------------------------------------");
    Stopwatch stopwatch = Stopwatch.createStarted();
    Observable.just(THE_SENTENCE).repeat(numberOfSentences).toBlocking().forEach(theSentence -> sysout(
            "Result arrived: " + theSentence + " -> " + fastWordCount(theSentence) + " words"));
    System.out.println("Elapsed: " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "ms");
    System.out.println("Fast... just as warm-up.");

    System.out.println("-----------------------------------------------------------------------");
    stopwatch = Stopwatch.createStarted();
    Observable.just(THE_SENTENCE).repeat(numberOfSentences).toBlocking().forEach(theSentence -> sysout(
            "Result arrived: " + theSentence + " -> " + fastWordCount(theSentence) + " words"));
    System.out.println("Elapsed: " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "ms");
    System.out.println("Fast, again. After warm-up our 'reference'.");

    /*// w  ww.  j  av  a  2 s .  co m
    System.out.println("-----------------------------------------------------------------------");
    Thread.sleep(5000);
    stopwatch = Stopwatch.createStarted();
    Observable.just(THE_SENTENCE).repeat(numberOfSentences)
        .toBlocking()
        .forEach(theSentence -> sysout("Result arrived: " + theSentence + " -> " + wordCountWithCachedThread(theSentence)
                .toBlocking()
                .first()
                + " words"));
    System.out.println("Elapsed: " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "ms");
    System.out.println("Fast 2... Same as first, but executed on separate, cached thread. Just to see the overhead.");
    */

    System.out.println("-----------------------------------------------------------------------");
    Thread.sleep(5000);
    stopwatch = Stopwatch.createStarted();
    Observable.just(THE_SENTENCE).repeat(numberOfSentences).toBlocking().forEach(theSentence -> sysout(
            "Result arrived: " + theSentence + " -> " + sometimesSlowWordCount(theSentence) + " words"));
    System.out.println("Elapsed: " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "ms");
    System.out.println("Sometimes slow... Now we have sometimes some latency. How to deal with this?");

    System.out.println("-----------------------------------------------------------------------");
    Thread.sleep(5000);
    stopwatch = Stopwatch.createStarted();
    Observable.just(THE_SENTENCE).repeat(numberOfSentences).toBlocking()
            .forEach(theSentence -> sysout("Result arrived: " + theSentence + " -> "
                    + sometimesSlowWordCountWithBackupRequests(theSentence) + " words"));
    System.out.println("Elapsed: " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "ms");
    System.out.println(
            "Sometimes slow with backup requests... pretty fast, again. Backup requests work! Whew... ");
}

From source file:com.jejking.hh.nord.gazetteer.osm.poi.WritePointsOfInterest.java

/**
 * @param args//www. j  av a2  s  .c  o  m
 */
public static void main(String[] args) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
    GraphDatabaseService graph = new GraphDatabaseFactory().newEmbeddedDatabase(args[0]);
    registerShutdownHook(graph);

    WritePointsOfInterest.writePointsOfInterest(geometryFactory, graph);
    System.out.println(
            "Wrote points of interest. Elapsed time: " + stopwatch.elapsed(TimeUnit.SECONDS) + " seconds");
}