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:me.bramhaag.discordselfbot.commands.admin.CommandPing.java

@Command(name = "ping")
public void execute(@NonNull Message message, @NonNull TextChannel channel, @NonNull String[] args) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    message.editMessage("`Waiting...`").queue(m -> {
        stopwatch.stop();/*  w  w  w  .  j  a  va 2s.co  m*/
        m.editMessage(new EmbedBuilder().setTitle(Constants.PONG_EMOTE + " Pong!", null)
                .addField("Response time (Bot)", stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms", true)
                .addField("Response time (API)", message.getJDA().getPing() + " ms", true)
                .setFooter("Ping | " + Util.generateTimestamp(), null).build())
                .queue(embed -> embed.delete().queueAfter(Constants.REMOVE_TIME_LONG, TimeUnit.SECONDS));
    });
}

From source file:com.facebook.buck.distributed.ClientStatsTracker.java

public synchronized void stopTimer(DistBuildClientStat stat) {
    Objects.requireNonNull(stopwatchesByType.get(stat),
            "Cannot stop timer for stat: [" + stat + "] as it was not started.");

    Stopwatch stopwatch = stopwatchesByType.get(stat);
    stopwatch.stop();/* w w w  .ja va  2  s  .c  o m*/
    long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
    durationsMsByType.put(stat, elapsed);
}

From source file:net.monofraps.gradlebukkit.tasks.RunBukkit.java

@TaskAction
public void doWork() throws IOException, LifecycleExecutionException, InterruptedException {
    final int latestDownloadedBuild = findBukkitBuildToRun();
    if (latestDownloadedBuild < 0) {
        throw new LifecycleExecutionException("Couldn't find Bukkit jar to run.");
    }//ww  w  . j av  a2s .co m

    final String bukkitJarName = "bukkit-" + latestDownloadedBuild + ".jar";

    final RemoteDebugging debugConfiguration = ((Bukkit) getProject().getExtensions().getByName("bukkit"))
            .getDebugSettings();
    final String debuggingArguments = (debugConfiguration == null) ? "" : debugConfiguration.getJvmArguments();

    final ProcessBuilder bukkitProcessBuilder = new ProcessBuilder("java", debuggingArguments, "-jar",
            bukkitJarName);
    bukkitProcessBuilder.environment().putAll(System.getenv());
    bukkitProcessBuilder.directory(new File(getProject().getBuildDir(), "bukkit"));

    getLogger().lifecycle("Starting Bukkit...");
    final Process bukkitProcess = bukkitProcessBuilder.start();

    final StreamGrabber errorGrabber = new StreamGrabber(bukkitProcess.getErrorStream());
    final StreamGrabber stdoutGrabber = new StreamGrabber(bukkitProcess.getInputStream());
    errorGrabber.start();
    stdoutGrabber.start();

    final PrintWriter stdinWriter = new PrintWriter(bukkitProcess.getOutputStream());
    String line;
    while ((line = System.console().readLine()) != null && !line.equals("gterm")) {
        stdinWriter.write(line);
        stdinWriter.write("\n");
        stdinWriter.flush();

        try {
            bukkitProcess.exitValue();
            break;
        } catch (final IllegalThreadStateException ignored) {
        }
    }

    try {
        bukkitProcess.exitValue();
    } catch (final IllegalThreadStateException ex) {
        final Thread joiner = new Thread() {
            @Override
            public void run() {
                bukkitProcess.destroy();
            }
        };

        joiner.start();
        final Stopwatch stopwatch = new Stopwatch();
        stopwatch.start();
        while (joiner.isAlive()) {
            if (stopwatch.elapsed(TimeUnit.MILLISECONDS) > 60) {
                joiner.interrupt();
                joiner.join(5000);
            }
            Thread.sleep(500);
        }
        stopwatch.stop();
    }

    getLogger().lifecycle("Bukkit process exited with exit code " + bukkitProcess.exitValue());
}

From source file:me.lazerka.gae.jersey.oauth2.google.TokenVerifierGoogleRemote.java

@Override
public GoogleUserPrincipal verify(String authToken) throws IOException, InvalidKeyException {
    logger.trace("Requesting endpoint to validate token");

    URL url = UriBuilder.fromUri(TOKEN_INFO).queryParam("id_token", authToken).build().toURL();

    HTTPRequest httpRequest = new HTTPRequest(url, GET, validateCertificate());

    Stopwatch stopwatch = Stopwatch.createStarted();
    HTTPResponse response = urlFetchService.fetch(httpRequest);
    logger.debug("Remote call took {}ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));

    int responseCode = response.getResponseCode();
    String content = new String(response.getContent(), UTF_8);

    if (responseCode != 200) {
        logger.warn("{}: {}", responseCode, content);

        String msg = "Endpoint response code " + responseCode;

        // Something is wrong with our request.
        // If signature is invalid, then response code is 403.
        if (responseCode >= 400 && responseCode < 500) {
            try {
                TokenErrorResponse tokenErrorResponse = jsonFactory.fromString(content,
                        TokenErrorResponse.class);
                msg += ": " + tokenErrorResponse.getErrorDescription();
            } catch (IOException e) {
                logger.warn("Cannot parse response as " + TokenErrorResponse.class.getSimpleName());
            }/* w ww  .  j av a 2 s  .c  o m*/
        }

        throw new InvalidKeyException(msg);
    }

    // Signature verification is done remotely (the whole point of this class).
    // Expiration verification is done

    Payload payload = jsonFactory.fromString(content, Payload.class);

    // Issuers verification have been done remotely.

    Set<String> trustedClientIds = Collections.singleton(oauthClientId);
    // Note containsAll.
    if (!trustedClientIds.containsAll(payload.getAudienceAsList())) {
        throw new InvalidKeyException("Audience invalid");
    }

    if (!payload.getEmailVerified()) {
        throw new InvalidKeyException("Email not verified");
    }

    return new GoogleUserPrincipal(payload.getSubject(), payload.getEmail());
}

From source file:com.twitter.distributedlog.util.MonitoredFuturePool.java

@Override
public <T> Future<T> apply(Function0<T> function0) {
    if (traceTaskExecution) {
        taskPendingCounter.inc();/* w ww .  j  a  v  a  2  s.c  o m*/
        Stopwatch taskEnqueueStopwatch = Stopwatch.createStarted();
        Future<T> futureResult = futurePool.apply(new TimedFunction0<T>(function0));
        taskEnqueueTime.registerSuccessfulEvent(taskEnqueueStopwatch.elapsed(TimeUnit.MICROSECONDS));
        futureResult.ensure(new com.twitter.util.Function0<BoxedUnit>() {
            @Override
            public BoxedUnit apply() {
                taskPendingCounter.dec();
                return null;
            }
        });
        return futureResult;
    } else {
        return futurePool.apply(function0);
    }
}

From source file:org.terasology.polyworld.TriangleLookup.java

/**
 * Creates a lookup image for the graph's region triangles
 *//*w  w w.ja v  a  2 s.c om*/
public TriangleLookup(Graph graph) {

    bounds = graph.getBounds();

    // TODO: maybe use USHORT_GRAY instead
    image = new BufferedImage(bounds.width(), bounds.height(), BufferedImage.TYPE_INT_RGB);
    Graphics2D g = image.createGraphics();
    g.translate(-bounds.minX(), -bounds.minY());

    try {
        Stopwatch sw = Stopwatch.createStarted();
        triangles = drawTriangles(g, graph);
        logger.debug("Cached {} triangle lookups in {}ms.", triangles.size(),
                sw.elapsed(TimeUnit.MILLISECONDS));
    } finally {
        g.dispose();
    }

    dataBuffer = (DataBufferInt) image.getRaster().getDataBuffer();
}

From source file:org.glowroot.container.impl.LocalContainer.java

@Override
public void executeAppUnderTest(Class<? extends AppUnderTest> appClass) throws Exception {
    ClassLoader previousContextClassLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(isolatedWeavingClassLoader);
    executingAppThreads.add(Thread.currentThread());
    try {//from  w  w  w  . ja v a  2  s  .  c o  m
        AppUnderTest app = isolatedWeavingClassLoader.newInstance(appClass, AppUnderTest.class);
        app.executeApp();
    } finally {
        executingAppThreads.remove(Thread.currentThread());
        Thread.currentThread().setContextClassLoader(previousContextClassLoader);
    }
    // wait for all traces to be stored
    Stopwatch stopwatch = Stopwatch.createStarted();
    while (traceService.getNumPendingCompleteTransactions() > 0 && stopwatch.elapsed(SECONDS) < 5) {
        Thread.sleep(10);
    }
}

From source file:benchmarkio.producer.activemq.ActiveMQMessageProducer.java

private void produce(final String topic, final TextMessage message) {
    for (int i = 0; i < numberOfMessagesToProduce; i++) {
        try {//from ww  w  .j a  v a  2s. co  m
            log.debug("Publishing message to ActiveMQ topic {}\n{}", topic, message);

            // Start
            final Stopwatch stopwatch = Stopwatch.createStarted();

            producer.send(message);

            // End
            stopwatch.stop();
            histogram.recordValue(stopwatch.elapsed(Consts.TIME_UNIT_FOR_REPORTING));

        } catch (final Exception e) {
            log.error("Error publishing message to ActiveMQ topic {}\n{}", topic, message.toString());
        }
    }

    log.info("Finished production of {} messages", numberOfMessagesToProduce);
}

From source file:cc.kave.commons.pointsto.evaluation.TimeEvaluation.java

private DescriptiveStatistics measurePointerAnalysis(List<Context> contexts, PointsToAnalysisFactory ptFactory,
        MutableLong sink) {/*from   w ww. j a  va 2 s  .co  m*/
    DescriptiveStatistics stats = new DescriptiveStatistics();

    for (Context context : contexts) {
        PointsToAnalysis ptAnalysis = ptFactory.create();
        Stopwatch watch = Stopwatch.createStarted();
        PointsToContext ptContext = ptAnalysis.compute(context);
        watch.stop();
        sink.add(ptContext.hashCode());
        long time = watch.elapsed(TimeUnit.MICROSECONDS);
        stats.addValue(time);

        analysisTimes.add(new AnalysisTimeEntry(ptFactory.getName(),
                context.getTypeShape().getTypeHierarchy().getElement(), stmtCounts.get(context), time));
    }

    return stats;
}

From source file:me.lazerka.gae.jersey.oauth2.facebook.FacebookFetcher.java

String fetch(URL url) throws IOException, InvalidKeyException {
    logger.trace("Requesting endpoint to validate token");

    HTTPRequest httpRequest = new HTTPRequest(url, GET, validateCertificate());

    Stopwatch stopwatch = Stopwatch.createStarted();
    HTTPResponse response = urlFetchService.fetch(httpRequest);
    logger.debug("Remote call took {}ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));

    int responseCode = response.getResponseCode();
    String content = new String(response.getContent(), UTF_8);

    if (responseCode != 200) {
        logger.warn("{}: {}", responseCode, content);

        String msg = "Endpoint response code " + responseCode;

        // Something is wrong with our request.
        // If signature is invalid, then response code is 403.
        if (responseCode >= 400 && responseCode < 500) {
            try {
                JsonNode tree = jackson.readTree(content);
                JsonNode error = tree.findPath("error");
                if (!error.isMissingNode()) {
                    msg += ": " + error.findPath("message").textValue();
                }//from  w  w  w .  j a v a  2 s .  c  o  m
            } catch (IOException e) {
                logger.warn("Cannot parse response as error");
            }
        }

        throw new InvalidKeyException(msg);
    }

    return content;
}