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.graylog2.shared.initializers.PeriodicalsService.java

@Override
protected void shutDown() throws Exception {
    for (Periodical periodical : periodicals.getAllStoppedOnGracefulShutdown()) {
        LOG.info("Shutting down periodical [{}].", periodical.getClass().getCanonicalName());
        Stopwatch s = Stopwatch.createStarted();

        // Cancel future executions.
        Map<Periodical, ScheduledFuture> futures = periodicals.getFutures();
        if (futures.containsKey(periodical)) {
            futures.get(periodical).cancel(false);

            s.stop();/*from ww w.j  a  va  2s  . c  om*/
            LOG.info("Shutdown of periodical [{}] complete, took <{}ms>.",
                    periodical.getClass().getCanonicalName(), s.elapsed(TimeUnit.MILLISECONDS));
        } else {
            LOG.error("Could not find periodical [{}] in futures list. Not stopping execution.",
                    periodical.getClass().getCanonicalName());
        }
    }
}

From source file:org.glowroot.central.GrpcServer.java

void close(boolean jvmTermination) throws InterruptedException {
    if (confDirWatchExecutor != null && !jvmTermination) {
        // shutdownNow() is needed here to send interrupt to conf dir watching thread
        confDirWatchExecutor.shutdownNow();
        if (!confDirWatchExecutor.awaitTermination(10, SECONDS)) {
            throw new IllegalStateException("Timed out waiting for conf dir watching thread to terminate");
        }//w  w  w .jav a  2  s  .  c o m
    }

    // immediately start sending "shutting-down" responses for new downstream requests
    // and wait for existing downstream requests to complete before proceeding
    downstreamService.stopSendingDownstreamRequests();

    // "shutting-down" responses will continue to be sent for new downstream requests until
    // ClusterManager is closed at the very end of CentralModule.shutdown(), which will give
    // time for agents to reconnect to a new central cluster node, and for the UI to retry
    // for a few seconds if it receives a "shutting-down" response

    if (httpsServer != null) {
        // stop accepting new requests
        httpsServer.shutdown();
    }
    if (httpServer != null) {
        // stop accepting new requests
        httpServer.shutdown();
    }
    Stopwatch stopwatch = Stopwatch.createStarted();
    if (httpsServer != null) {
        // wait for existing requests to complete
        while (stopwatch.elapsed(SECONDS) < 5) {
            if (httpsServer.isTerminated()) {
                break;
            }
            Thread.sleep(10);
        }
    }
    if (httpServer != null) {
        // wait for existing requests to complete
        while (stopwatch.elapsed(SECONDS) < 5) {
            if (httpServer.isTerminated()) {
                break;
            }
            Thread.sleep(10);
        }
    }
    if (httpsServer != null && !httpsServer.isTerminated()) {
        httpsServer.shutdownNow();
    }
    if (httpServer != null && !httpServer.isTerminated()) {
        httpServer.shutdownNow();
    }
    stopwatch = Stopwatch.createStarted();
    if (httpsServer != null && !httpsServer.isTerminated() && !httpsServer.awaitTermination(5, SECONDS)) {
        throw new IllegalStateException("Timed out waiting for grpc server to terminate");
    }
    long remainingMillis = Math.max(0, 5000 - stopwatch.elapsed(MILLISECONDS));
    if (httpServer != null && !httpServer.isTerminated()
            && !httpServer.awaitTermination(remainingMillis, MILLISECONDS)) {
        throw new IllegalStateException("Timed out waiting for grpc server to terminate");
    }
}

From source file:demos.SynchronousInsert.java

public void run() {
    logger.info("Preparing to insert metric data points");

    Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
    Session session = cluster.connect("demo");
    PreparedStatement insert = session
            .prepare("insert into metric_data (metric_id, time, value) values (?, ?, ?)");
    Random random = new Random();
    DateTime time = DateTime.now().minusYears(1);

    Stopwatch stopwatch = new Stopwatch().start();
    for (int i = 0; i < NUM_INSERTS; ++i) {
        String metricId = "metric-" + Math.abs(random.nextInt() % NUM_METRICS);
        double value = random.nextDouble();
        session.execute(insert.bind(metricId, time.toDate(), value));
        time = time.plusSeconds(10);/*from w ww  . j a  v  a  2 s. co  m*/
    }
    stopwatch.stop();

    logger.info("Finished inserting {} data points in {} ms", NUM_INSERTS,
            stopwatch.elapsed(TimeUnit.MILLISECONDS));
}

From source file:demos.SynchronousRead.java

public void run() {
    logger.info("Preparing to read data points");

    Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
    Session session = cluster.connect("demo");
    PreparedStatement query = session.prepare(
            "SELECT metric_id, time, value FROM metric_data WHERE metric_id = ? AND time >= ? AND time <= ?");
    DateTime end = DateTime.now();/*from w  ww .j a va2 s .co m*/
    DateTime start = end.minusYears(1);
    List<DataPoint> dataPoints = new ArrayList<>();

    Stopwatch stopwatch = new Stopwatch().start();
    for (int i = 0; i < NUM_METRICS; ++i) {
        ResultSet resultSet = session.execute(query.bind("metric-" + i, start.toDate(), end.toDate()));
        resultSet.forEach(
                row -> dataPoints.add(new DataPoint(row.getString(0), row.getDate(1), row.getDouble(2))));
    }
    stopwatch.stop();

    logger.info("Retrieved {} data points in {} ms", dataPoints.size(),
            stopwatch.elapsed(TimeUnit.MILLISECONDS));
}

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

@Override
public Enrichment get(final long timeout, final TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
    final Stopwatch waiting = Stopwatch.createStarted();
    LOGGER.trace("Waiting for acknowledgment...");
    try {//from w  w  w. ja  v  a  2  s. c om
        final Enrichment replyOrNull = this.delegate.get(timeout, unit);
        logAcknowledgeReception(waiting);
        return replyOrNull;
    } catch (final Exception e) {
        LOGGER.trace("Did not receive acknowledgment after {} milliseconds",
                waiting.elapsed(TimeUnit.MILLISECONDS));
        throw e;
    }
}

From source file:com.google.caliper.runner.worker.WorkerRunner.java

/**
 * Starts up the worker process and runs it to completion, processing data received from it with
 * the provided {@link WorkerProcessor}. Returns the result object produced by the processor.
 *//*from   w ww . j a  v  a 2 s . c  o m*/
public R runWorker() {
    checkState(worker.state() == State.NEW, "You can only invoke the run loop once");

    // logger must be opened before starting worker
    WorkerOutputLogger workerLogger = worker.outputLogger();
    try {
        workerLogger.open();
    } catch (IOException e) {
        throw processor.newWorkerException(
                String.format("Failed to open output logger for worker [%s].", worker.name()), e);
    }
    outputFile = workerLogger.outputFile();

    worker.startAsync();
    try {
        workerLogger.printHeader();

        long timeLimitNanos = processor.timeLimit().to(NANOSECONDS);
        Stopwatch stopwatch = Stopwatch.createUnstarted();

        worker.awaitRunning();
        worker.sendRequest();

        stopwatch.start();
        while (!done) {
            Worker.StreamItem item;
            try {
                item = worker.readItem(timeLimitNanos - stopwatch.elapsed(NANOSECONDS), NANOSECONDS);
            } catch (InterruptedException e) {
                // Someone has asked us to stop (via Futures.cancel?).
                if (!doneProcessing) {
                    throw processor
                            .newWorkerException(formatError(processor.getInterruptionErrorMessage(worker)), e);
                }
                logger.log(Level.WARNING,
                        // Yes, we're doing the formatting eagerly here even though the log level might not
                        // be enabled. It seems like a small sacrifice in this case for more readable code.
                        formatError(
                                "Worker [%s] cancelled before completing normally, but after getting results.",
                                worker));
                done = true;
                break;
            }

            switch (item.kind()) {
            case DATA:
                doneProcessing = processor.handleMessage(item.content(), worker);
                if (doneProcessing) {
                    // The worker should be done now; give it WORKER_CLEANUP_DURATION nanos to finish
                    // shutting down.
                    long cleanupTimeNanos = MILLISECONDS.toNanos(WORKER_CLEANUP_DURATION.getMillis());
                    timeLimitNanos = stopwatch.elapsed(NANOSECONDS) + cleanupTimeNanos;
                }
                break;
            case EOF:
                // We consider EOF to be synonymous with worker shutdown
                if (!doneProcessing) {
                    throw processor.newWorkerException(
                            formatError(processor.getPrematureExitErrorMessage(worker)), null);
                }
                done = true;
                break;
            case TIMEOUT:
                if (!doneProcessing) {
                    throw processor.newWorkerException(formatError(processor.getTimeoutErrorMessage(worker)),
                            null);
                }
                logger.log(Level.WARNING,
                        formatError("Worker [%s] failed to exit cleanly within the allotted time.", worker));
                done = true;
                break;
            default:
                throw new AssertionError("Impossible item: " + item);
            }
        }

        return processor.getResult();
    } catch (WorkerException e) {
        throw e;
    } catch (Throwable e) {
        logger.severe(formatError("Unexpected error while running worker [%s].", worker));
        Throwables.throwIfUnchecked(e);
        throw new RuntimeException(e);
    } finally {
        worker.stopAsync();
        try {
            workerLogger.ensureFileIsSaved();
        } finally {
            workerLogger.close();
        }
    }
}

From source file:qa.qcri.nadeef.core.pipeline.ScopeOperator.java

/**
 * {@inheritDoc}//from  w  w w .j  ava 2s .  c om
 */
@Override
@SuppressWarnings("unchecked")
public Collection<Table> execute(Collection<Table> tables) throws Exception {
    Stopwatch stopwatch = Stopwatch.createStarted();
    ExecutionContext context = getCurrentContext();
    Rule rule = context.getRule();

    // Scope
    // Here the horizontalScope needs to be called before vertical Scope since
    // it may needs the attributes which are going to be removed from verticals scope.
    Collection<Table> horizontalScopeResult = rule.horizontalScope(tables);
    setPercentage(0.5f);
    long time = stopwatch.elapsed(TimeUnit.MILLISECONDS);
    long currentTime;

    Collection<Table> verticalScopeResult = rule.verticalScope(horizontalScopeResult);

    currentTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);

    PerfReport.appendMetric(PerfReport.Metric.HScopeTime, time);
    PerfReport.appendMetric(PerfReport.Metric.VScopeTime, currentTime - time);
    PerfReport.appendMetric(PerfReport.Metric.AfterScopeTuple, verticalScopeResult.size());

    Collection<Table> result = verticalScopeResult;

    // Block
    // Currently we don't support co-group, so once a rule is working with two tables we
    // ignore the block function.
    if (!rule.supportTwoTables()) {
        result = rule.block(verticalScopeResult);
        PerfReport.appendMetric(PerfReport.Metric.Blocks, result.size());
    }

    stopwatch.stop();
    return result;
}

From source file:ch.ge.ve.protopoc.service.simulation.ElectionAdministrationSimulator.java

public List<Long> getTally() throws InvalidDecryptionProofException {
    TallyData tallyData = bulletinBoardService.getTallyData();

    List<DecryptionProof> decryptionProofs = tallyData.getDecryptionProofs();
    List<BigInteger> publicKeyShares = tallyData.getPublicKeyShares();
    List<Encryption> finalShuffle = tallyData.getFinalShuffle();
    List<List<BigInteger>> partialDecryptions = tallyData.getPartialDecryptions();
    Stopwatch decryptionProofCheckWatch = Stopwatch.createStarted();
    if (!tallyingAuthoritiesAlgorithm.checkDecryptionProofs(decryptionProofs, publicKeyShares, finalShuffle,
            partialDecryptions)) {//from   www. j av a  2s  . c  o m
        throw new InvalidDecryptionProofException("An invalid decryption proof was found");
    }
    decryptionProofCheckWatch.stop();
    perfLog.info(String.format("Administration : checked decryption proofs in %dms",
            decryptionProofCheckWatch.elapsed(TimeUnit.MILLISECONDS)));

    List<BigInteger> decryptions = tallyingAuthoritiesAlgorithm.getDecryptions(finalShuffle,
            partialDecryptions);
    List<List<Boolean>> votes = tallyingAuthoritiesAlgorithm.getVotes(decryptions, totalCandidateCount);
    // Additional verifications on the votes validity may be performed here.
    return IntStream.range(0, totalCandidateCount)
            .mapToLong(i -> votes.stream().filter(vote -> vote.get(i)).count()).boxed()
            .collect(Collectors.toList());
}

From source file:org.apache.drill.exec.physical.impl.TopN.PriorityQueueTemplate.java

@Override
public void generate() throws SchemaChangeException {
    Stopwatch watch = new Stopwatch();
    watch.start();/*from  w  w  w. ja v  a 2 s  .  co m*/
    final DrillBuf drillBuf = allocator.buffer(4 * queueSize);
    finalSv4 = new SelectionVector4(drillBuf, queueSize, 4000);
    for (int i = queueSize - 1; i >= 0; i--) {
        finalSv4.set(i, pop());
    }
    logger.debug("Took {} us to generate output of {}", watch.elapsed(TimeUnit.MICROSECONDS),
            finalSv4.getTotalCount());
}

From source file:bear.main.CompileManager.java

public synchronized CompilationResult compileWithAll() {
    logger.info("compiling...");

    Stopwatch sw = Stopwatch.createStarted();

    if (lastCompilationResult != null && System.currentTimeMillis() - lastCompilationResult.timestamp() < 300) {
        logger.debug("cancelled compilation, up to date");
    } else {/*from   w  w w  . j av a2s.  c  o m*/
        lastCompilationResult = groovyCompiler.compile(dependenciesCL.or(getClass().getClassLoader()));
    }

    logger.info("compilation finished in {}s", LangUtils.millisToSec(sw.elapsed(TimeUnit.MILLISECONDS)));

    return lastCompilationResult;
}