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:org.opendaylight.controller.cluster.datastore.MemberNode.java

public void waitForMemberDown(String member) {
    Stopwatch sw = Stopwatch.createStarted();
    while (sw.elapsed(TimeUnit.SECONDS) <= 10) {
        CurrentClusterState state = Cluster.get(kit.getSystem()).state();
        for (Member m : state.getUnreachable()) {
            if (member.equals(m.getRoles().iterator().next())) {
                return;
            }//from   www . j  a  va 2  s.c o  m
        }

        for (Member m : state.getMembers()) {
            if (m.status() != MemberStatus.up() && member.equals(m.getRoles().iterator().next())) {
                return;
            }
        }

        Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
    }

    fail("Member " + member + " is now down");
}

From source file:benchmarkio.consumer.kafka.BlockingKafkaMessageConsumer.java

@Override
public Histogram call() throws Exception {
    int messageCount = 0;

    try {//from   ww  w  . ja  va 2  s. co m
        final ConsumerIterator<byte[], byte[]> it = stream.iterator();
        while (it.hasNext()) {
            try {
                // Start
                final Stopwatch stopwatch = Stopwatch.createStarted();

                final byte[] message = it.next().message();

                messageCount++;

                // End
                stopwatch.stop();
                histogram.recordValue(stopwatch.elapsed(Consts.TIME_UNIT_FOR_REPORTING));
            } catch (final Exception e) {
                logger.error("Error processing message", e);
            }
        }
    } catch (final ConsumerTimeoutException e) {
        // This is by purpose, hence no error logging.
        logger.info("Consumer was terminated through timeout");
    }

    logger.info("In total consumed {} messages", messageCount);

    return histogram;
}

From source file:com.dssmp.agent.tailing.AsyncPublisher.java

/**
 * @param timeout Use a value {@code <= 0} to wait indefinitely.
 * @param unit/*  ww  w.  ja  v a2 s. c  om*/
 * @return {@code true} if idle state was reached before the timeout
 *         expired, or {@code false} if idle state was not successfully
 *         reached.
 */
public boolean waitForIdle(long timeout, TimeUnit unit) {
    Stopwatch timer = Stopwatch.createStarted();
    while (!isIdle()) {
        long remaining = timeout > 0 ? (unit.toMillis(timeout) - timer.elapsed(TimeUnit.MILLISECONDS))
                : Long.MAX_VALUE;
        if (remaining <= 0)
            return false;
        long sleepTime = Math.min(MAX_SPIN_WAIT_TIME_MILLIS, remaining);
        logger.trace("{}: Waiting for idle state. Sleeping {}ms. {}", name(), sleepTime, toString());
        // Perform a check on any pending records in case it's time to publish them before sleeping
        queue.checkPendingRecords();
        try {
            Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
            // No need to make this method interruptible. Just return false signifying timeout.
            Thread.currentThread().interrupt();
            logger.trace("{}: Thread interrupted.", name(), e);
            return false;
        }
    }
    return true;
}

From source file:org.smartdeveloperhub.curator.connector.LoggedConnectorFuture.java

private void logAcknowledgeReception(final Stopwatch waiting) {
    LOGGER.trace("{} {} milliseconds",
            this.delegate.isCancelled() ? "Cancelled while waiting for acknowledgement for"
                    : "Received acknowledgement after ",
            waiting.elapsed(TimeUnit.MILLISECONDS));
}

From source file:pro.foundev.strategies.BenchmarkStrategy.java

private void exec(Runnable runnable, String name, int runs, BenchmarkReport report) {
    logger.info("Starting run of " + name);
    DescriptiveStatistics stats = new DescriptiveStatistics();

    Stopwatch timer = new Stopwatch();
    for (int i = 0; i < runs; i++) {
        timer.start();/*  w  ww  . ja  v a  2s .co m*/
        runnable.run();
        timer.stop();
        logger.info("Time to execute load run #" + i + " it took " + timer);
        stats.addValue(timer.elapsed(TimeUnit.MILLISECONDS));
        timer.reset();
    }
    logger.info("Finished run of " + name);
    report.addLine(name, stats.getMin(), stats.getMax(), stats.getPercentile(50), stats.getPercentile(90),
            stats.getMean());
}

From source file:com.facebook.buck.cli.DistBuildLogsCommand.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("Successfully downloaded build information in [%d millis].",
                stopwatch.elapsed(TimeUnit.MILLISECONDS)));

        stopwatch.reset().start();/*w ww .  ja  v  a 2s.  co m*/
        List<BuildSlaveRunId> buildSlaves = buildJob.getBuildSlaves().stream().map(x -> x.getBuildSlaveRunId())
                .collect(Collectors.toList());
        stdout.println(String.format("Materializing logs for [%d] BuildSlaves. (%s)", buildSlaves.size(),
                Joiner.on(", ").join(buildSlaves)));
        Path logDir = params.getInvocationInfo().get().getLogDirectoryPath();
        ProjectFilesystem filesystem = params.getCell().getFilesystem();
        BuildSlaveLogsMaterializer materializer = new BuildSlaveLogsMaterializer(service, filesystem, logDir);
        List<BuildSlaveRunId> notMaterialized = materializer
                .fetchAndMaterializeAvailableLogs(buildJob.getStampedeId(), buildSlaves);

        if (notMaterialized.isEmpty()) {
            console.printSuccess(String.format("Successfully materialized all logs into [%s] in [%d millis].",
                    logDir.toAbsolutePath().toString(), stopwatch.elapsed(TimeUnit.MILLISECONDS)));
            return ExitCode.SUCCESS;
        } else if (notMaterialized.size() == buildSlaves.size()) {
            console.printErrorText(String.format("Failed to materialize all logs. Duration=[%d millis].",
                    stopwatch.elapsed(TimeUnit.MILLISECONDS)));
            // TODO: buck(team) proper disambiguate between user errors and fatals
            return ExitCode.BUILD_ERROR;
        } else {
            stdout.println(console.getAnsi()
                    .asWarningText(String.format("Materialized [%d] out of [%d] logs into [%s] in [%d millis].",
                            buildSlaves.size() - notMaterialized.size(), buildSlaves.size(),
                            logDir.toAbsolutePath().toString(), stopwatch.elapsed(TimeUnit.MILLISECONDS))));
            return ExitCode.BUILD_ERROR;
        }
    }
}

From source file:com.spotify.heroic.metric.generated.GeneratedBackend.java

@Override
public AsyncFuture<FetchData> fetch(MetricType source, Series series, DateRange range,
        FetchQuotaWatcher watcher, QueryOptions options) {
    final Stopwatch w = Stopwatch.createStarted();

    if (source == MetricType.POINT) {
        final List<Point> data = generator.generatePoints(series, range, watcher);
        final QueryTrace trace = new QueryTrace(FETCH, w.elapsed(TimeUnit.NANOSECONDS));
        final ImmutableList<Long> times = ImmutableList.of(trace.getElapsed());
        final List<MetricCollection> groups = ImmutableList.of(MetricCollection.points(data));
        return async.resolved(new FetchData(series, times, groups, trace));
    }// w w w. j ava 2 s.co m

    if (source == MetricType.EVENT) {
        final List<Event> data = generator.generateEvents(series, range, watcher);
        final QueryTrace trace = new QueryTrace(FETCH, w.elapsed(TimeUnit.NANOSECONDS));
        final ImmutableList<Long> times = ImmutableList.of(trace.getElapsed());
        final List<MetricCollection> groups = ImmutableList.of(MetricCollection.events(data));
        return async.resolved(new FetchData(series, times, groups, trace));
    }

    throw new IllegalArgumentException("unsupported source: " + source);
}

From source file:org.hyperledger.perftest.SendTransactionThroughputMeasure.java

private List<Long> measureSingleThreaded() throws Exception {
    List<Long> results = new ArrayList<>(getRounds());
    for (int i = 0; i < getRounds(); i++) {
        System.out.println("Measuring round " + i);
        List<Transaction> txsForOneRound = txs.get(i);
        System.gc();//from   www.j  a v  a 2s  .c o  m
        System.gc();
        System.gc();
        System.gc();
        System.gc();
        Stopwatch watch = Stopwatch.createStarted();
        for (Transaction tx : txsForOneRound) {
            api.sendTransaction(tx);
        }
        watch.stop();
        results.add(watch.elapsed(TimeUnit.MILLISECONDS));
    }
    return results;
}

From source file:org.apache.bookkeeper.proto.PacketProcessorBase.java

protected void sendResponse(final int rc, final OpStatsLogger statsLogger, Object response) {
    final Stopwatch writeStopwatch = Stopwatch.createStarted();
    channel.write(response).addListener(new ChannelFutureListener() {
        @Override//from w w  w  .  ja  v a 2 s .c  o m
        public void operationComplete(ChannelFuture channelFuture) throws Exception {

            long writeMicros = writeStopwatch.elapsed(TimeUnit.MICROSECONDS);
            if (!channelFuture.isSuccess()) {
                channelWriteOpStatsLogger.registerFailedEvent(writeMicros);
            } else {
                channelWriteOpStatsLogger.registerSuccessfulEvent(writeMicros);
            }

            long requestMicros = enqueueStopwatch.elapsed(TimeUnit.MICROSECONDS);
            if (BookieProtocol.EOK == rc) {
                statsLogger.registerSuccessfulEvent(requestMicros);
            } else {
                statsLogger.registerFailedEvent(requestMicros);
            }
        }
    });
}

From source file:org.openqa.selenium.internal.selenesedriver.ScriptExecutor.java

@SuppressWarnings({ "unchecked" })
private <T> T evaluateScript(String script) {
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.start();//from  www  . j  a va2s.co  m
    String result = selenium.getEval(script);
    stopWatch.stop();

    Response response = new JsonToBeanConverter().convert(Response.class, result);
    new ErrorHandler().throwIfResponseFailed(response, stopWatch.elapsed(MILLISECONDS));
    return (T) response.getValue();
}