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.google.cloud.genomics.dataflow.functions.CombineShardsFn.java

static void dumpStats(long processedReads, Stopwatch timer) {
    LOG.info("Processed " + processedReads + " records in " + timer + ". Speed: "
            + processedReads / timer.elapsed(TimeUnit.SECONDS) + " reads/sec");

}

From source file:org.opendaylight.controller.cluster.datastore.IntegrationTestKit.java

public static void verifyShardStats(DistributedDataStore datastore, String shardName,
        ShardStatsVerifier verifier) throws Exception {
    ActorContext actorContext = datastore.getActorContext();

    Future<ActorRef> future = actorContext.findLocalShardAsync(shardName);
    ActorRef shardActor = Await.result(future, Duration.create(10, TimeUnit.SECONDS));

    AssertionError lastError = null;
    Stopwatch sw = Stopwatch.createStarted();
    while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
        ShardStats shardStats = (ShardStats) actorContext.executeOperation(shardActor,
                Shard.GET_SHARD_MBEAN_MESSAGE);

        try {/*from w  ww . j a va2  s  .  c  om*/
            verifier.verify(shardStats);
            return;
        } catch (AssertionError e) {
            lastError = e;
            Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
        }
    }

    throw lastError;
}

From source file:org.opendaylight.protocol.pcep.pcc.mock.PCCMockCommon.java

static TestingSessionListener checkSessionListenerNotNull(final TestingSessionListenerFactory factory,
        final String localAddress) {
    Stopwatch sw = Stopwatch.createStarted();
    TestingSessionListener listener = null;
    while (sw.elapsed(TimeUnit.SECONDS) <= 1000) {
        listener = factory.getSessionListenerByRemoteAddress(InetAddresses.forString(localAddress));
        if (listener == null) {
            Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
        } else {/*from  w  w w .  ja v  a 2  s.  co  m*/
            return listener;
        }
    }
    throw new NullPointerException();
}

From source file:org.opendaylight.controller.cluster.datastore.MemberNode.java

public static void verifyNoShardPresent(DistributedDataStore datastore, String shardName) {
    Stopwatch sw = Stopwatch.createStarted();
    while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
        Optional<ActorRef> shardReply = datastore.getActorContext().findLocalShard(shardName);
        if (!shardReply.isPresent()) {
            return;
        }/* ww  w. j  a v a 2 s. c o m*/

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

    fail("Shard " + shardName + " is present");
}

From source file:org.glowroot.container.Threads.java

public static void moreAccurateSleep(int millis) throws InterruptedException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    if (millis > 10) {
        Thread.sleep(millis - 10);
    }/*  ww  w.j  a v  a2 s.  c  o  m*/
    while (stopwatch.elapsed(MILLISECONDS) < millis) {
        Thread.sleep(1);
    }
}

From source file:brooklyn.test.PerformanceTestUtils.java

/**
 * Creates a background thread that will log.info the CPU fraction usage repeatedly, sampling at the given period.
 * Callers <em>must</em> cancel the returned future, e.g. {@code future.cancel(true)}, otherwise it will keep
 * logging until the JVM exits./*w w  w . j av a2  s  .  c  om*/
 */
public static Future<?> sampleProcessCpuTime(final Duration period, final String loggingContext) {
    final ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, "brooklyn-sampleProcessCpuTime-" + loggingContext);
            thread.setDaemon(true); // let the JVM exit
            return thread;
        }
    });
    Future<?> future = executor.submit(new Runnable() {
        @Override
        public void run() {
            try {
                long prevCpuTime = getProcessCpuTime();
                if (prevCpuTime == -1) {
                    LOG.warn("ProcessCPuTime not available; cannot sample; aborting");
                    return;
                }
                while (true) {
                    Stopwatch stopwatch = Stopwatch.createStarted();
                    Thread.sleep(period.toMilliseconds());
                    long currentCpuTime = getProcessCpuTime();

                    long elapsedTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);
                    double fractionCpu = (elapsedTime > 0)
                            ? ((double) currentCpuTime - prevCpuTime)
                                    / TimeUnit.MILLISECONDS.toNanos(elapsedTime)
                            : -1;
                    prevCpuTime = currentCpuTime;

                    LOG.info("CPU fraction over last {} was {} ({})", new Object[] {
                            Time.makeTimeStringRounded(elapsedTime), fractionCpu, loggingContext });
                }
            } catch (InterruptedException e) {
                return; // graceful termination
            } finally {
                executor.shutdownNow();
            }
        }
    });
    return future;
}

From source file:org.opendaylight.controller.cluster.datastore.MemberNode.java

public static void verifyRaftState(DistributedDataStore datastore, String shardName, RaftStateVerifier verifier)
        throws Exception {
    ActorContext actorContext = datastore.getActorContext();

    Future<ActorRef> future = actorContext.findLocalShardAsync(shardName);
    ActorRef shardActor = Await.result(future, Duration.create(10, TimeUnit.SECONDS));

    AssertionError lastError = null;
    Stopwatch sw = Stopwatch.createStarted();
    while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
        OnDemandRaftState raftState = (OnDemandRaftState) actorContext.executeOperation(shardActor,
                GetOnDemandRaftState.INSTANCE);

        try {/*w  w w  . java 2s.co m*/
            verifier.verify(raftState);
            return;
        } catch (AssertionError e) {
            lastError = e;
            Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
        }
    }

    throw lastError;
}

From source file:org.catrobat.catroid.common.bluetooth.ConnectionDataLogger.java

private static ArrayList<byte[]> waitForMessages(BlockingQueue<byte[]> messages, int messageByteOffset,
        int messageCountToWaitFor) {

    ArrayList<byte[]> m = new ArrayList<byte[]>();
    Stopwatch stopWatch = Stopwatch.createStarted();

    do {/*w w w.ja  va  2  s.  c  o m*/
        byte[] message = pollMessage(messages, TIMEOUT_SECONDS - (int) stopWatch.elapsed(TimeUnit.SECONDS));
        if (message == null) {
            return m;
        }
        m.add(BluetoothTestUtils.getSubArray(message, messageByteOffset));
    } while (m.size() < messageCountToWaitFor && stopWatch.elapsed(TimeUnit.SECONDS) < TIMEOUT_SECONDS);

    return m;
}

From source file:processing.BaselineCalculator.java

private static List<int[]> getPopularTags(BookmarkReader reader, int sampleSize, int limit) {
    timeString = "";
    List<int[]> tags = new ArrayList<int[]>();
    Stopwatch timer = new Stopwatch();
    timer.start();/*from   w ww .  j  av  a 2  s . com*/

    int[] tagIDs = getPopularTagList(reader, limit);

    timer.stop();
    long trainingTime = timer.elapsed(TimeUnit.MILLISECONDS);
    timer = new Stopwatch();
    timer.start();
    for (int j = 0; j < sampleSize; j++) {
        tags.add(tagIDs);
    }
    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 / sampleSize) + "\n";
    timeString += ("Total time: " + (trainingTime + testTime) + "\n");
    return tags;
}

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

public static Future<?> sampleProcessCpuTime(final Duration period, final String loggingContext,
        final List<Double> cpuFractions) {
    final ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactory() {
        @Override//from   ww  w  .  ja v  a2 s  . c  om
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, "brooklyn-sampleProcessCpuTime-" + loggingContext);
            thread.setDaemon(true); // let the JVM exit
            return thread;
        }
    });
    Future<?> future = executor.submit(new Runnable() {
        @Override
        public void run() {
            try {
                long prevCpuTime = getProcessCpuTime();
                if (prevCpuTime == -1) {
                    LOG.warn("ProcessCPuTime not available; cannot sample; aborting");
                    return;
                }
                while (true) {
                    Stopwatch stopwatch = Stopwatch.createStarted();
                    Thread.sleep(period.toMilliseconds());
                    long currentCpuTime = getProcessCpuTime();

                    long elapsedTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);
                    double fractionCpu = (elapsedTime > 0)
                            ? ((double) currentCpuTime - prevCpuTime)
                                    / TimeUnit.MILLISECONDS.toNanos(elapsedTime)
                            : -1;
                    prevCpuTime = currentCpuTime;

                    LOG.info("CPU fraction over last {} was {} ({})", new Object[] {
                            Time.makeTimeStringRounded(elapsedTime), fractionCpu, loggingContext });

                    if (cpuFractions != null) {
                        cpuFractions.add(fractionCpu);
                    }
                }
            } catch (InterruptedException e) {
                return; // graceful termination
            } finally {
                executor.shutdownNow();
            }
        }
    });
    return future;
}