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.github.benmanes.caffeine.profiler.ProfilerHook.java

private void scheduleStatusTask() {
    Stopwatch stopwatch = Stopwatch.createStarted();
    Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(() -> {
        long count = calls.longValue();
        long rate = count / stopwatch.elapsed(TimeUnit.SECONDS);
        System.out.printf("%s - %,d [%,d / sec]%n", stopwatch, count, rate);
    }, DISPLAY_DELAY_SEC, DISPLAY_DELAY_SEC, TimeUnit.SECONDS);
}

From source file:com.twitter.distributedlog.io.LZ4CompressionCodec.java

@Override
public byte[] compress(byte[] data, int offset, int length, OpStatsLogger compressionStat) {
    Preconditions.checkNotNull(data);/*  w  w w  .  ja  v a  2s .  c o m*/
    Preconditions.checkArgument(offset >= 0 && offset < data.length);
    Preconditions.checkArgument(length >= 0);
    Preconditions.checkNotNull(compressionStat);

    Stopwatch watch = Stopwatch.createStarted();
    byte[] compressed = compressor.compress(data, offset, length);
    compressionStat.registerSuccessfulEvent(watch.elapsed(TimeUnit.MICROSECONDS));
    return compressed;
}

From source file:org.apache.james.queue.api.DelayedMailQueueContract.java

@Test
default void delayShouldAtLeastBeTheOneSpecified() throws Exception {
    long delay = 1L;
    TimeUnit unit = TimeUnit.SECONDS;
    Stopwatch started = Stopwatch.createStarted();

    getMailQueue().enQueue(defaultMail().build(), delay, unit);

    getMailQueue().deQueue();/* w ww .ja  v  a 2 s . co m*/
    assertThat(started.elapsed(TimeUnit.MILLISECONDS)).isGreaterThanOrEqualTo(unit.toMillis(delay));
}

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

@RequiresNonNull("startupLogger")
private static Session connect(CentralConfiguration centralConfig) throws Exception {
    Session session = null;/*  w w w  .j  a v  a2  s .  c o m*/
    // instantiate the default timestamp generator (AtomicMonotonicTimestampGenerator) only once
    // since it calls com.datastax.driver.core.ClockFactory.newInstance() via super class
    // (AbstractMonotonicTimestampGenerator) which logs whether using native clock or not,
    // which is useful, but annoying when waiting for cassandra to start up and the message gets
    // logged over and over and over
    TimestampGenerator defaultTimestampGenerator = Policies.defaultTimestampGenerator();

    RateLimitedLogger waitingForCassandraLogger = new RateLimitedLogger(CentralModule.class);
    RateLimitedLogger waitingForCassandraReplicasLogger = new RateLimitedLogger(CentralModule.class);

    Stopwatch stopwatch = Stopwatch.createStarted();
    NoHostAvailableException lastException = null;
    while (stopwatch.elapsed(MINUTES) < 30) {
        try {
            String keyspace = centralConfig.cassandraKeyspace();
            if (session == null) {
                ConsistencyLevel writeConsistencyLevelOverride;
                if (centralConfig.cassandraWriteConsistencyLevel() == centralConfig
                        .cassandraReadConsistencyLevel()) {
                    writeConsistencyLevelOverride = null;
                } else {
                    writeConsistencyLevelOverride = centralConfig.cassandraWriteConsistencyLevel();
                }
                session = new Session(createCluster(centralConfig, defaultTimestampGenerator).connect(),
                        keyspace, writeConsistencyLevelOverride,
                        // max concurrent queries before throwing BusyPoolException is "max
                        // requests per connection" + "max queue size" (which are set to
                        // cassandraMaxConcurrentQueries and cassandraMaxConcurrentQueries * 2
                        // respectively)
                        centralConfig.cassandraMaxConcurrentQueries() * 3);
            }
            String cassandraVersion = verifyCassandraVersion(session);
            KeyspaceMetadata keyspaceMetadata = checkNotNull(
                    session.getCluster().getMetadata().getKeyspace(keyspace));
            String replicationFactor = keyspaceMetadata.getReplication().get("replication_factor");
            if (replicationFactor == null) {
                replicationFactor = "unknown";
            }
            startupLogger.info(
                    "connected to Cassandra (version {}), using keyspace '{}'"
                            + " (replication factor {}) and consistency level {}",
                    cassandraVersion, keyspace, replicationFactor,
                    centralConfig.cassandraConsistencyLevelDisplay());
            return session;
        } catch (NoHostAvailableException e) {
            startupLogger.debug(e.getMessage(), e);
            lastException = e;
            if (session == null) {
                waitingForCassandraLogger.info("waiting for Cassandra ({})...",
                        Joiner.on(",").join(centralConfig.cassandraContactPoint()));
            } else {
                waitingForCassandraReplicasLogger.info(
                        "waiting for enough Cassandra replicas"
                                + " to run queries at consistency level {} ({})...",
                        centralConfig.cassandraConsistencyLevelDisplay(),
                        Joiner.on(",").join(centralConfig.cassandraContactPoint()));
            }
            SECONDS.sleep(1);
        } catch (RuntimeException e) {
            // clean up
            if (session != null) {
                session.getCluster().close();
            }
            throw e;
        }
    }
    // clean up
    if (session != null) {
        session.getCluster().close();
    }
    checkNotNull(lastException);
    throw lastException;
}

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

public final T loadOffline(CacheKey key) {
    final Stopwatch w = Stopwatch.createStarted();
    T value = cache.getUnchecked(key);/*from w  w  w. j  a va  2  s  .  co m*/
    offline.add(w.elapsed(TimeUnit.MILLISECONDS));
    return value;
}

From source file:com.minestellar.moon.MinestellarMoon.java

@EventHandler
public void postInit(FMLPostInitializationEvent event) {
    Stopwatch stopwatch = Stopwatch.createStarted();

    MinestellarMoon.proxy.postInit(event);

    log.info("PostInitialization Completed in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms.");
}

From source file:org.smartdeveloperhub.vocabulary.publisher.handlers.ProbeTracerHandler.java

@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final Stopwatch watch = MoreAttachments.getStopwatch(exchange);
    watch.stop();/*from w w  w  . j a v  a2s.  com*/
    LOGGER.trace("[{}][{}] Processing took {} {}", exchange.getRequestPath(), exchange.getRelativePath(),
            watch.elapsed(this.unit), this.unit.toString());
    this.next.handleRequest(exchange);
}

From source file:brooklyn.entity.rebind.persister.BrooklynMementoPersisterToFile.java

@Override
public void delta(Delta delta, PersistenceExceptionHandler exceptionHandler) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    synchronized (mutex) {
        long timeObtainedMutex = stopwatch.elapsed(TimeUnit.MILLISECONDS);
        super.delta(delta, exceptionHandler);
        long timeDeltad = stopwatch.elapsed(TimeUnit.MILLISECONDS);
        writeMemento();//from  w w w .  j ava 2 s .  c  o  m
        long timeWritten = stopwatch.elapsed(TimeUnit.MILLISECONDS);

        if (LOG.isDebugEnabled())
            LOG.debug("Checkpointed memento; total={}ms, obtainingMutex={}ms, " + "delta'ing={}ms, writing={}",
                    new Object[] { timeWritten, timeObtainedMutex, (timeDeltad - timeObtainedMutex),
                            (timeWritten - timeDeltad) });
    }
}

From source file:brooklyn.entity.rebind.persister.BrooklynMementoPersisterToFile.java

@Override
public void checkpoint(BrooklynMemento newMemento, PersistenceExceptionHandler exceptionHandler) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    synchronized (mutex) {
        long timeObtainedMutex = stopwatch.elapsed(TimeUnit.MILLISECONDS);
        super.checkpoint(newMemento, exceptionHandler);
        long timeCheckpointed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
        writeMemento();//  ww w. j  av  a 2  s .com
        long timeWritten = stopwatch.elapsed(TimeUnit.MILLISECONDS);

        if (LOG.isDebugEnabled())
            LOG.debug(
                    "Checkpointed memento; total={}ms, obtainingMutex={}ms, "
                            + "checkpointing={}ms, writing={}ms",
                    new Object[] { timeWritten, timeObtainedMutex, (timeCheckpointed - timeObtainedMutex),
                            (timeWritten - timeCheckpointed) });
    }
}

From source file:org.apache.drill.exec.physical.impl.sort.SortTemplate.java

@Override
public void sort(SelectionVector4 vector4, VectorContainer container) {
    Stopwatch watch = new Stopwatch();
    watch.start();//from  w  w  w .  ja  v a  2 s.  com
    QuickSort qs = new QuickSort();
    qs.sort(this, 0, vector4.getTotalCount());
    logger.debug("Took {} us to sort {} records", watch.elapsed(TimeUnit.MICROSECONDS),
            vector4.getTotalCount());
}