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

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

Introduction

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

Prototype

@CheckReturnValue
public static Stopwatch createStarted() 

Source Link

Document

Creates (and starts) a new stopwatch using System#nanoTime as its time source.

Usage

From source file:fr.ens.transcriptome.aozan.collectors.AbstractFastqProcessThread.java

@Override
public void run() {

    // Timer/*from w  w  w.j a  va  2  s.co m*/
    final Stopwatch timer = Stopwatch.createStarted();

    notifyStartLogger();

    try {
        // Launch process treatment related to each collector
        process();

        setSuccess(true);

    } catch (final AozanException e) {
        setException(e);
    } finally {

        final String duration = toTimeHumanReadable(timer.elapsed(TimeUnit.MILLISECONDS));
        timer.stop();

        notifyEndLogger(duration);
    }

}

From source file:org.hyperledger.core.bitcoin.BitcoinPersistentBlocks.java

@Override
public StoredTransaction readTransaction(TID hash) throws HyperLedgerException {
    nRead++;/*from  w  w  w.j a va2s  .  c om*/
    Stopwatch watch = Stopwatch.createStarted();
    try {
        byte[] data = store
                .get(OrderedMapStoreKey.createKey(OrderedMapStoreKey.KeyType.TX, hash.unsafeGetArray()));
        if (data != null) {
            StoredTransaction t = StoredTransaction.fromLevelDB(data);
            if (!t.getID().equals(hash)) {
                throw new HyperLedgerException("Database inconsistency in TX " + hash);
            }
            return t;
        }
        return null;
    } finally {
        readTime += watch.stop().elapsed(TimeUnit.MILLISECONDS);
    }
}

From source file:com.vmware.photon.controller.common.metrics.RpcMetricInterceptor.java

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    Stopwatch stopwatch = Stopwatch.createStarted();
    String methodName = invocation.getMethod().getName();
    try {/*w w w. ja  va  2s  . c om*/
        logger.info("Starting call to {}", methodName);
        return invocation.proceed();
    } catch (Throwable t) {
        exceptions.mark();
        logger.info("Caught exception during {}: {}", methodName, t);
        throw t;
    } finally {
        duration.update(stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS);
        logger.info("Finished call to {}", methodName);
    }
}

From source file:nl.knaw.huygens.timbuctoo.tools.process.Pipeline.java

@Override
public void call() throws Exception {
    Stopwatch stopWatch = Stopwatch.createStarted();
    for (Task task : tasks) {
        LOG.info(task.getDescription());
        task.call();/*  ww  w. j  a va 2 s . c o m*/
    }
    stopWatch.stop();
    LOG.info("Time used: {}", stopWatch);
}

From source file:org.glowroot.agent.it.harness.impl.TraceCollector.java

Trace getCompletedTrace(@Nullable String transactionType, @Nullable String transactionName, int timeout,
        TimeUnit unit) throws InterruptedException {
    if (transactionName != null) {
        checkNotNull(transactionType);//from  ww w. j  a  v  a 2s.co  m
    }
    Stopwatch stopwatch = Stopwatch.createStarted();
    while (stopwatch.elapsed(unit) < timeout) {
        for (Trace trace : traces) {
            if (!trace.getHeader().getPartial()
                    && (transactionType == null
                            || trace.getHeader().getTransactionType().equals(transactionType))
                    && (transactionName == null
                            || trace.getHeader().getTransactionName().equals(transactionName))) {
                return trace;
            }
        }
        MILLISECONDS.sleep(10);
    }
    if (transactionName != null) {
        throw new IllegalStateException("No trace was collected for transaction type \"" + transactionType
                + "\" and transaction name \"" + transactionName + "\"");
    } else if (transactionType != null) {
        throw new IllegalStateException("No trace was collected for transaction type: " + transactionType);
    } else {
        throw new IllegalStateException("No trace was collected");
    }
}

From source file:com.edduarte.argus.diff.DifferenceMatcher.java

@Override
public Set<DifferenceMatcher.Result> call() {
    Stopwatch sw = Stopwatch.createStarted();

    Set<Result> matchedDiffs = new ConcurrentHashSet<>();

    DifferenceAction lastAction = DifferenceAction.nothing;
    BloomFilter<String> lastBloomFilter = null;
    for (Difference r : differences) {
        if (lastAction == DifferenceAction.nothing || r.getAction() != lastAction) {
            // reset the bloom filter being used
            lastBloomFilter = BloomFilter.create((from, into) -> into.putUnencodedChars(from), 10);
            lastAction = r.getAction();/*from ww w.j a va  2s.co m*/
        }
        BloomFilter<String> bloomFilter = lastBloomFilter;
        bloomFilter.put(r.getOccurrenceText());

        // check if AT LEAST ONE of the keywords has ALL of its words
        // contained in the diff text
        keywords.parallelStream().unordered().filter(kw -> kw.textStream().allMatch(bloomFilter::mightContain))
                .map(kw -> new Pair<>(r, kw))
                .filter((pair) -> pair.b().textStream().anyMatch(pair.a().getOccurrenceText()::equals))
                .map((pair) -> {
                    Difference diff = pair.a();
                    Keyword keyword = pair.b();
                    DifferenceAction i = diff.getAction();
                    if (i == DifferenceAction.inserted && !ignoreAdded) {
                        return new Result(diff.getAction(), keyword, diff.getSnippet());

                    } else if (i == DifferenceAction.deleted && !ignoreRemoved) {
                        return new Result(diff.getAction(), keyword, diff.getSnippet());
                    }
                    return null;
                }).filter(diff -> diff != null).forEach(matchedDiffs::add);
    }

    sw.stop();
    logger.info("Completed difference matching for keywords '{}' in {}", keywords.toString(), sw.toString());
    return matchedDiffs;
}

From source file:org.glowroot.agent.it.harness.Threads.java

public static void preShutdownCheck(Collection<Thread> preExistingThreads) throws InterruptedException {
    // give the test 5 seconds to shutdown any threads they may have created, e.g. give tomcat
    // time to shutdown when testing tomcat plugin
    Stopwatch stopwatch = Stopwatch.createStarted();
    List<Thread> nonPreExistingThreads;
    List<Thread> rogueThreads;
    do {/*from  ww  w  . j av a 2 s  .c o  m*/
        nonPreExistingThreads = getNonPreExistingThreads(preExistingThreads);
        rogueThreads = Lists.newArrayList();
        for (Thread thread : nonPreExistingThreads) {
            if (isRogueThread(thread)) {
                rogueThreads.add(thread);
            }
        }
        // check total number of threads to make sure Glowroot is not creating too many
        //
        // currently, the eight threads are:
        //
        // Glowroot-Background-0
        // Glowroot-Background-1
        // H2 Log Writer GLOWROOT
        // H2 File Lock Watchdog <lock db file>
        // Glowroot-GRPC-Worker-ELG-0
        // Glowroot-GRPC-Executor-0
        // Generate Seed
        // threadDeathWatcher-2-1
        // grpc-shared-destroyer-0
        if (rogueThreads.isEmpty() && nonPreExistingThreads.size() <= 8) {
            // success
            return;
        }
        // wait a few milliseconds before trying again
        MILLISECONDS.sleep(10);
    } while (stopwatch.elapsed(SECONDS) < 10);
    // failure
    if (!rogueThreads.isEmpty()) {
        throw new RogueThreadsException(rogueThreads);
    } else {
        throw new TooManyThreadsException(nonPreExistingThreads);
    }
}

From source file:com.edduarte.vokter.diff.DifferenceMatcher.java

@Override
public Set<DifferenceMatcher.Result> call() {
    Stopwatch sw = Stopwatch.createStarted();

    Set<Result> matchedDiffs = new ConcurrentHashSet<>();

    DifferenceEvent lastAction = DifferenceEvent.nothing;
    BloomFilter<String> lastBloomFilter = null;
    for (Difference r : differences) {
        if (lastAction == DifferenceEvent.nothing || r.getAction() != lastAction) {
            // reset the bloom filter being used
            lastBloomFilter = BloomFilter.create((from, into) -> into.putUnencodedChars(from), 10);
            lastAction = r.getAction();//from   w w  w.  java 2  s.  c o m
        }
        BloomFilter<String> bloomFilter = lastBloomFilter;
        bloomFilter.put(r.getOccurrenceText());

        // check if AT LEAST ONE of the keywords has ALL of its words
        // contained in the diff text
        keywords.parallelStream().unordered().filter(kw -> kw.textStream().allMatch(bloomFilter::mightContain))
                .map(kw -> new Pair<>(r, kw))
                .filter((pair) -> pair.b().textStream().anyMatch(pair.a().getOccurrenceText()::equals))
                .map((pair) -> {
                    Difference diff = pair.a();
                    Keyword keyword = pair.b();
                    DifferenceEvent i = diff.getAction();
                    if (i == DifferenceEvent.inserted && !ignoreAdded) {
                        return new Result(diff.getAction(), keyword, diff.getSnippet());

                    } else if (i == DifferenceEvent.deleted && !ignoreRemoved) {
                        return new Result(diff.getAction(), keyword, diff.getSnippet());
                    }
                    return null;
                }).filter(diff -> diff != null).forEach(matchedDiffs::add);
    }

    sw.stop();
    logger.info("Completed difference matching for keywords '{}' in {}", keywords.toString(), sw.toString());
    return matchedDiffs;
}

From source file:com.facebook.buck.cli.DistBuildKillCommand.java

@Override
public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception {
    Console console = params.getConsole();
    PrintStream stdout = console.getStdOut();
    StampedeId stampedeId = getStampedeId();

    try (DistBuildService service = DistBuildFactory.newDistBuildService(params)) {
        stdout.println(String.format("Fetching build information for StampedeId=[%s].", stampedeId.getId()));
        Stopwatch stopwatch = Stopwatch.createStarted();
        BuildJob buildJob = service.getCurrentBuildJobState(getStampedeId());

        stdout.println(String.format("The build is currently in status [%s:%s].",
                buildJob.getStatus().toString(), buildJob.getStatusMessage()));
        if (BuildStatusUtil.isTerminalBuildStatus(buildJob.getStatus())) {
            console.printSuccess(//ww w .  j a  va  2 s . co  m
                    String.format("Build is already finished so doing nothing. Took [%d millis] to execute.",
                            stopwatch.elapsed(TimeUnit.MILLISECONDS)));
            // Returning SUCCESS instead of NOTHING_TO_DO to possibly avoid breaking some contract
            return ExitCode.SUCCESS;
        }

        String statusMessage = String.format(
                "Build killed via 'buck distbuild kill' command by user=[%s] from host=[%s].",
                System.getProperty("user.name"), HostnameFetching.getHostname());
        stdout.println(String.format("Killing the build and setting statusMessage to [%s].", statusMessage));

        service.setFinalBuildStatus(stampedeId, BuildStatus.FAILED, statusMessage);
        console.printSuccess(String.format("Successfully killed the build in [%d millis].",
                stopwatch.elapsed(TimeUnit.MILLISECONDS)));
        return ExitCode.SUCCESS;
    }
}

From source file:com.isotrol.impe3.pms.core.impl.TimingAspect.java

@Around("@within(org.springframework.stereotype.Service)")
public Object time(ProceedingJoinPoint pjp) throws Throwable {
    final Stopwatch w = Stopwatch.createStarted();
    try {/*from  w  ww  .j  a  v  a2s.c  o  m*/
        return pjp.proceed();
    } finally {
        final long t = w.elapsed(TimeUnit.MILLISECONDS);
        final String key = pjp.getTarget().getClass().getName() + "." + pjp.getSignature().toShortString();
        map.add(key, t);
        if (t > 500) {
            logger.warn(String.format("[%s] took [%d] ms", key, t));
        }
    }
}