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:io.scigraph.owlapi.loader.BatchOwlLoader.java

public static void load(OwlLoadConfiguration config) throws InterruptedException, ExecutionException {
    Injector i = Guice.createInjector(new OwlLoaderModule(config),
            new Neo4jModule(config.getGraphConfiguration()));
    BatchOwlLoader loader = i.getInstance(BatchOwlLoader.class);
    logger.info("Loading ontologies...");
    Stopwatch timer = Stopwatch.createStarted();
    // TODO catch exception and delete the incomplete graph through the graph location
    loader.loadOntology();/*  w  ww  .ja  v a  2 s  .c om*/
    DB mapDb = i.getInstance(DB.class);
    mapDb.close();
    logger.info(format("Loading took %d minutes", timer.elapsed(TimeUnit.MINUTES)));
}

From source file:com.google.devtools.build.android.AndroidResourceMerger.java

public static UnwrittenMergedAndroidData mergeData(ListeningExecutorService executorService,
        List<? extends SerializedAndroidData> transitive, List<? extends SerializedAndroidData> direct,
        ParsedAndroidData primary, Path primaryManifest, boolean allowPrimaryOverrideAll,
        AndroidDataDeserializer deserializer) throws MergingException {
    Stopwatch timer = Stopwatch.createStarted();
    try {/*from   w ww.  j a  v  a  2s .co m*/
        AndroidDataMerger merger = AndroidDataMerger.createWithPathDeduplictor(executorService, deserializer);
        return merger.loadAndMerge(transitive, direct, primary, primaryManifest, allowPrimaryOverrideAll);
    } finally {
        logger.fine(String.format("merge finished in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
    }
}

From source file:com.omnius.watcheye.util.PollingVerifier.java

public static void pollingVerify(Runnable verify) {
    AssertionError lastVerification;
    Stopwatch watch = Stopwatch.createStarted();
    do {/*from  ww w .j a  va2  s. c  o  m*/
        try {
            verify.run();
            return;
        } catch (AssertionError e) {
            lastVerification = e;
            try {
                Thread.sleep(VERIFYING_POLL_PERIOD_IN_MILLIS);
            } catch (InterruptedException e1) {
                Throwables.propagate(e1);
            }
        }
    } while (watch.elapsed(TimeUnit.MILLISECONDS) < VERIFYING_POLL_TIMEOUT_IN_MILLIS);
    throw lastVerification;
}

From source file:org.apache.brooklyn.test.performance.PerformanceMeasurer.java

/**
 * Runs a performance test. Repeatedly executes the given job. It measuring either the time it takes for
 * many iterations, or the number of iterations it can execute in a fixed time.
 */// w  w w.j  a va2 s .c o  m
public static PerformanceTestResult run(PerformanceTestDescriptor options) {
    options.seal();
    long nextLogTime = (options.logInterval == null) ? Long.MAX_VALUE : options.logInterval.toMilliseconds();

    // Try to force garbage collection before the test, so it interferes less with the measurement.
    System.gc();
    System.gc();

    // Run some warm-up cycles.
    Stopwatch warmupWatch = Stopwatch.createStarted();
    int warmupCounter = 0;

    while ((options.warmup != null) ? options.warmup.isLongerThan(warmupWatch)
            : warmupCounter < options.warmupIterations) {
        if (warmupWatch.elapsed(TimeUnit.MILLISECONDS) >= nextLogTime) {
            LOG.info("Warm-up " + options.summary + " iteration=" + warmupCounter + " at "
                    + Time.makeTimeStringRounded(warmupWatch));
            nextLogTime += options.logInterval.toMilliseconds();
        }
        options.job.run();
        warmupCounter++;
    }
    warmupWatch.stop();

    // Run the actual test (for the given duration / iterations); then wait for completionLatch (if supplied).
    nextLogTime = (options.logInterval == null) ? Long.MAX_VALUE : options.logInterval.toMilliseconds();
    int counter = 0;
    Histogram histogram = new Histogram();
    List<Double> cpuSampleFractions = Lists.newLinkedList();
    Future<?> sampleCpuFuture = null;
    if (options.sampleCpuInterval != null) {
        sampleCpuFuture = PerformanceTestUtils.sampleProcessCpuTime(options.sampleCpuInterval, options.summary,
                cpuSampleFractions);
    }

    try {
        long preCpuTime = PerformanceTestUtils.getProcessCpuTime();
        Stopwatch watch = Stopwatch.createStarted();

        while ((options.duration != null) ? options.duration.isLongerThan(watch)
                : counter < options.iterations) {
            if (warmupWatch.elapsed(TimeUnit.MILLISECONDS) >= nextLogTime) {
                LOG.info(
                        options.summary + " iteration=" + counter + " at " + Time.makeTimeStringRounded(watch));
                nextLogTime += options.logInterval.toMilliseconds();
            }
            long before = watch.elapsed(TimeUnit.NANOSECONDS);
            options.job.run();
            if (options.histogram) {
                histogram.add(watch.elapsed(TimeUnit.NANOSECONDS) - before, TimeUnit.NANOSECONDS);
            }
            counter++;
        }

        if (options.completionLatch != null) {
            try {
                boolean success = options.completionLatch.await(options.completionLatchTimeout.toMilliseconds(),
                        TimeUnit.MILLISECONDS);
                if (!success) {
                    fail("Timeout waiting for completionLatch: test=" + options + "; counter=" + counter);
                }
            } catch (InterruptedException e) {
                throw Exceptions.propagate(e);
            }
        }
        watch.stop();
        long postCpuTime = PerformanceTestUtils.getProcessCpuTime();

        // Generate the results
        PerformanceTestResult result = new PerformanceTestResult();
        result.warmup = Duration.of(warmupWatch);
        result.warmupIterations = warmupCounter;
        result.duration = Duration.of(watch);
        result.iterations = counter;
        result.ratePerSecond = (((double) counter) / watch.elapsed(TimeUnit.MILLISECONDS)) * 1000;
        result.cpuTotalFraction = (watch.elapsed(TimeUnit.NANOSECONDS) > 0 && preCpuTime >= 0)
                ? ((double) postCpuTime - preCpuTime) / watch.elapsed(TimeUnit.NANOSECONDS)
                : -1;
        if (options.histogram) {
            result.histogram = histogram;
        }
        if (options.sampleCpuInterval != null) {
            result.cpuSampleFractions = cpuSampleFractions;
        }
        result.minAcceptablePerSecond = options.minAcceptablePerSecond;

        // Persist the results
        if (options.persister != null) {
            options.persister.persist(new Date(), options, result);
        }

        // Fail if we didn't meet the minimum performance requirements
        if (options.minAcceptablePerSecond != null && options.minAcceptablePerSecond > result.ratePerSecond) {
            fail("Performance too low: test=" + options + "; result=" + result);
        }

        return result;

    } finally {
        if (sampleCpuFuture != null) {
            sampleCpuFuture.cancel(true);
        }
    }
}

From source file:processing.ActCalculator.java

private static List<Map<Integer, Double>> startActCreation(BookmarkReader reader, int sampleSize,
        boolean sorting, boolean userBased, boolean resBased, int dVal, int beta) {
    timeString = "";
    int size = reader.getUserLines().size();
    int trainSize = size - sampleSize;

    Stopwatch timer = new Stopwatch();
    timer.start();//from w w  w.  j  av  a 2 s . c  o  m
    ActCalculator calculator = new ActCalculator(reader, trainSize, dVal, beta, userBased, resBased);
    timer.stop();
    long trainingTime = timer.elapsed(TimeUnit.MILLISECONDS);
    List<Map<Integer, Double>> results = new ArrayList<Map<Integer, Double>>();
    if (trainSize == size) {
        trainSize = 0;
    }

    timer = new Stopwatch();
    timer.start();
    for (int i = trainSize; i < size; i++) { // the test-set
        UserData data = reader.getUserLines().get(i);
        Map<Integer, Double> map = calculator.getRankedTagList(data.getUserID(), data.getWikiID(), sorting);
        results.add(map);
    }
    timer.stop();
    long testTime = timer.elapsed(TimeUnit.MILLISECONDS);
    timeString += ("Full training time: " + trainingTime + "\n");
    timeString += ("Full test time: " + testTime + "\n");
    timeString += ("Average test time: " + testTime / (double) sampleSize) + "\n";
    timeString += ("Total time: " + (trainingTime + testTime) + "\n");
    return results;
}

From source file:edu.illinois.keshmesh.detector.Main.java

private static BasicAnalysisData initBytecodeAnalysis(IJavaProject javaProject, Reporter reporter,
        ConfigurationOptions configurationOptions) throws WALAInitializationException {
    KeshmeshCGModel model;/*from   w w w .  ja  va2  s. c om*/
    try {
        String exclusionsFileName = FileProvider
                .getFileFromPlugin(Activator.getDefault(), "EclipseDefaultExclusions.txt").getAbsolutePath();
        model = new KeshmeshCGModel(javaProject, exclusionsFileName,
                configurationOptions.getObjectSensitivityLevel());
        Stopwatch stopWatch = Stopwatch.createStarted();
        model.buildGraph();
        stopWatch.stop();
        reporter.report(new KeyValuePair("CALL_GRAPH_CONSTRUCTION_TIME_IN_MILLISECONDS",
                String.valueOf(stopWatch.elapsed(TimeUnit.MILLISECONDS))));
        reportEntryPointStatistics(reporter, model.getEntryPoints());
        dumpEntryPoints(model.getEntryPoints());
    } catch (Exception e) {
        throw new Exceptions.WALAInitializationException(e);
    }
    CallGraph callGraph = model.getGraph();
    reportCallGraphStatistics(reporter, callGraph);
    PointerAnalysis pointerAnalysis = model.getPointerAnalysis();
    HeapModel heapModel = pointerAnalysis.getHeapModel();
    BasicHeapGraph heapGraph = new BasicHeapGraph(pointerAnalysis, callGraph);
    if (configurationOptions.shouldDumpHeapGraph()) {
        dumpHeapGraph(heapGraph);
    }
    reporter.report(
            new KeyValuePair("NUMBER_OF_NODES_OF_HEAP_GRAPH", String.valueOf(heapGraph.getNumberOfNodes())));
    if (!hasShownGraphs) {
        try {
            DisplayUtils.displayGraph(callGraph);
            DisplayUtils.displayGraph(heapGraph);
            hasShownGraphs = true;
        } catch (WalaException e) {
            throw new WALAInitializationException(e);
        }
    }
    IClassHierarchy classHierarchy = model.getClassHierarchy();
    reporter.report(new KeyValuePair("NUMBER_OF_CLASSES", String.valueOf(classHierarchy.getNumberOfClasses())));
    return new BasicAnalysisData(classHierarchy, callGraph, pointerAnalysis, heapModel, heapGraph);
}

From source file:org.testfx.util.WaitForAsyncUtils.java

/**
 * Waits for given condition {@link Callable} to return (pull) {@code true}, otherwise times
 * out with {@link TimeoutException}. The condition will be evaluated at least once. The method
 * will wait for the last condition to finish after a timeout.
 *
 * @param timeout the timeout/* w  ww.  jav  a  2 s .  c om*/
 * @param timeUnit the time unit
 * @param condition the condition
 * @throws TimeoutException
 */
public static void waitFor(long timeout, TimeUnit timeUnit, Callable<Boolean> condition)
        throws TimeoutException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    while (!callConditionAndReturnResult(condition)) {
        sleep(CONDITION_SLEEP_IN_MILLIS, MILLISECONDS);
        if (stopwatch.elapsed(timeUnit) > timeout) {
            throw new TimeoutException();
        }
    }
}

From source file:com.codereligion.cherry.benchmark.BenchmarkRunner.java

public static Func1<Input, Observable<Output>> benchMark() {
    return new Func1<Input, Observable<Output>>() {
        @Override/*from  w  w  w  .j  av  a  2s  .  c  o m*/
        public Observable<Output> call(final Input input) {
            final Output output = Output.from(input);

            output.withGuavaContestant(benchMark(input.getRepetitions(), input.getGuavaResult()));
            output.withCherryContestant(benchMark(input.getRepetitions(), input.getCherryResult()));

            return Observable.just(output);
        }

        private ContestantResult benchMark(final long repetitions, final Contestant contestant) {

            int checkInt = 0;
            final Stopwatch stopwatch = Stopwatch.createUnstarted();
            final ContestantResult contestantResult = ContestantResult.from(contestant);

            for (long reps = 0; reps < repetitions; reps++) {

                System.gc();
                stopwatch.start();
                checkInt |= contestant.run();
                stopwatch.stop();

                final long timeInNanos = stopwatch.elapsed(TimeUnit.NANOSECONDS);
                contestantResult.addRunTime(timeInNanos);
                stopwatch.reset();
            }

            System.out.println("check int:" + checkInt);

            return contestantResult;
        }
    };
}

From source file:com.palantir.atlasdb.keyvalue.impl.ProfilingKeyValueService.java

private static void logTime(String method, Stopwatch stopwatch) {
    log.trace("Call to KVS.{} took {} ms.", method, stopwatch.elapsed(TimeUnit.MILLISECONDS));
}

From source file:org.glowroot.tests.WebDriverSetup.java

private static Container createContainer(int uiPort, File testDir) throws Exception {
    File adminFile = new File(testDir, "admin.json");
    Files.asCharSink(adminFile, UTF_8).write("{\"web\":{\"port\":" + uiPort + "}}");
    Container container;/*www .  ja  v  a 2  s.  c o m*/
    if (Containers.useJavaagent()) {
        container = new JavaagentContainer(testDir, true, ImmutableList.of());
    } else {
        container = new LocalContainer(testDir, true, ImmutableMap.of());
    }
    // wait for UI to be available (UI starts asynchronously in order to not block startup)
    CloseableHttpClient httpClient = HttpClients.custom().setRedirectStrategy(new DefaultRedirectStrategy())
            .build();
    Stopwatch stopwatch = Stopwatch.createStarted();
    Exception lastException = null;
    while (stopwatch.elapsed(SECONDS) < 10) {
        HttpGet request = new HttpGet("http://localhost:" + uiPort);
        try (CloseableHttpResponse response = httpClient.execute(request);
                InputStream content = response.getEntity().getContent()) {
            ByteStreams.exhaust(content);
            lastException = null;
            break;
        } catch (Exception e) {
            lastException = e;
        }
    }
    httpClient.close();
    if (lastException != null) {
        throw new IllegalStateException("Timed out waiting for Glowroot UI", lastException);
    }
    return container;
}