Example usage for com.google.common.base Stopwatch createStarted

List of usage examples for com.google.common.base Stopwatch createStarted

Introduction

In this page you can find the example usage for com.google.common.base Stopwatch createStarted.

Prototype

@CheckReturnValue
public static Stopwatch createStarted() 

Source Link

Document

Creates (and starts) a new stopwatch using System#nanoTime as its time source.

Usage

From source file:com.google.pubsub.clients.gcloud.CPSPublisherTask.java

@Override
public void run() {
    try {/*from  ww w .  j  ava 2  s. c  o  m*/
        List<Message> messages = new ArrayList<>(batchSize);
        String sendTime = String.valueOf(System.currentTimeMillis());
        for (int i = 0; i < batchSize; i++) {
            messages.add(Message.builder(payload).addAttribute("sendTime", sendTime)
                    .addAttribute("clientId", id.toString())
                    .addAttribute("sequenceNumber", Integer.toString(getAndIncrementNumberOfMessages()))
                    .build());
        }
        Stopwatch stopwatch = Stopwatch.createStarted();
        pubSub.publish(topic, messages);
        stopwatch.stop();
        metricsHandler.recordLatencyBatch(stopwatch.elapsed(TimeUnit.MILLISECONDS), batchSize);
    } catch (PubSubException e) {
        log.error("Publish request failed", e);
    }
}

From source file:org.lenskit.cli.commands.Predict.java

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public void execute(Namespace opts) throws IOException, RecommenderBuildException {
    Context ctx = new Context(opts);
    LenskitRecommenderEngine engine = ctx.loader.loadEngine();

    long user = ctx.options.getLong("user");
    List<Long> items = ctx.options.get("items");

    try (LenskitRecommender rec = engine.createRecommender()) {
        RatingPredictor pred = rec.getRatingPredictor();
        ItemNameDAO names = rec.get(ItemNameDAO.class);
        if (pred == null) {
            logger.error("recommender has no rating predictor");
            throw new UnsupportedOperationException("no rating predictor");
        }/*from   w  w  w .  j a  v  a  2 s.c  o  m*/

        logger.info("predicting {} items", items.size());
        Stopwatch timer = Stopwatch.createStarted();
        Map<Long, Double> preds = pred.predict(user, items);
        System.out.format("predictions for user %d:%n", user);
        for (Map.Entry<Long, Double> e : preds.entrySet()) {
            System.out.format("  %d", e.getKey());
            if (names != null) {
                System.out.format(" (%s)", names.getItemName(e.getKey()));
            }
            System.out.format(": %.3f", e.getValue());
            System.out.println();
        }
        timer.stop();
        logger.info("predicted for {} items in {}", items.size(), timer);
    }
}

From source file:com.facebook.buck.util.trace.uploader.Main.java

private int upload() {
    Stopwatch timer = Stopwatch.createStarted();
    try {//from w ww.jav a 2 s.  c  om
        OkHttpClient client = new OkHttpClient();
        HttpUrl url = HttpUrl.get(baseUrl).newBuilder().addQueryParameter("uuid", this.uuid)
                .addQueryParameter("trace_file_kind", this.traceFileKind).build();
        Path fileToUpload = traceFilePath;
        String mediaType = "application/data";
        String traceName = traceFilePath.getFileName().toString();
        boolean compressionEnabled = false;
        if (compressionType != null) {
            switch (compressionType) {
            case GZIP:
                fileToUpload = gzip(traceFilePath);
                mediaType = "application/json+gzip";
                traceName = traceName + ".gz";
                compressionEnabled = true;
                break;
            case NONE:
                break;
            }
        }

        log.format("Build ID: %s\n", uuid);
        log.format("Trace file: %s (%d) bytes\n", traceFilePath, Files.size(traceFilePath));
        if (compressionEnabled) {
            log.format("Compressed size: %d bytes\n", Files.size(fileToUpload));
        }
        log.format("Upload URL: %s\n", url);
        if (compressionEnabled) {
            log.format("Uploading compressed trace...");
        } else {
            log.format("Uploading trace...");
        }

        if (traceFileKind.equals("build_log")) {
            // Copy the log to a temp file in case buck is still writing to it.
            // TODO launch uploader from buck *after* logs are flushed
            Path tempFile = File.createTempFile(uuid, ".log").toPath();
            Files.copy(fileToUpload, tempFile, StandardCopyOption.REPLACE_EXISTING);
            fileToUpload = tempFile;
        }

        Request request = new Request.Builder().url(url)
                .post(new MultipartBody.Builder().setType(MultipartBody.FORM)
                        .addFormDataPart("trace_file", traceName,
                                RequestBody.create(MediaType.parse(mediaType), fileToUpload.toFile()))
                        .build())
                .build();

        try (Response response = client.newCall(request).execute()) {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode root = objectMapper.readTree(response.body().byteStream());

            if (root.get("success").asBoolean()) {
                log.format("Success!\nFind it at %s\n", root.get("content").get("uri").asText());
                return 0;
            } else {
                log.format("Failed!\nMessage: %s\n", root.get("error").asText());
                return 1;
            }
        }
    } catch (Exception e) {
        log.format("\nFailed to upload trace; %s\n", e.getMessage());
        return 1;
    } finally {
        log.format("Elapsed time: %d millis", timer.elapsed(TimeUnit.MILLISECONDS));
    }
}

From source file:com.github.nginate.commons.lang.await.Await.java

/**
 * Wait till the condition will become true during at most {@code timeout} millis. Will be checking the condition
 * each {@code waitStepMillis} millis.//from w ww .  j  a  va 2 s.c om
 *
 * @param timeout        max wait millis
 * @param waitStepMillis step wait millis
 * @param failureMessage message to see if waiting fails
 * @param condition      required condition
 * @throws ConditionTimeoutException if condition was not satisfied in configured period
 * @throws IllegalArgumentException  if step millis are more or equal to overall wait millis
 */
public static void waitUntil(int timeout, int waitStepMillis, String failureMessage,
        Callable<Boolean> condition) {
    Preconditions.checkArgument(waitStepMillis > 0, "step sleep time should be positive");
    Preconditions.checkArgument(waitStepMillis <= timeout, "step sleep time must be less or equal to timeout");

    Stopwatch stopwatch = Stopwatch.createStarted();
    while (stopwatch.elapsed(MILLISECONDS) < timeout) {
        try {
            if (condition.call()) {
                return;
            }
            sleep(waitStepMillis);
        } catch (Exception e) {
            throw propagate(e);
        }
    }
    throw new ConditionTimeoutException(failureMessage);
}

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

public void write(T val) {
    try {/*  w  w  w  .  j  ava 2 s.  c  om*/
        lock.writeLock().lockInterruptibly();
    } catch (InterruptedException e) {
        throw Exceptions.propagate(e);
    }
    try {
        Stopwatch stopwatch = Stopwatch.createStarted();

        // Write to the temp file, then atomically move it to the permanent file location
        Files.write(serializer.toString(val), tmpFile, Charsets.UTF_8);
        Files.move(tmpFile, file);
        modCount.incrementAndGet();

        if (LOG.isTraceEnabled())
            LOG.trace("Wrote {}, took {}; modified file {} times",
                    new Object[] { file, Time.makeTimeStringRounded(stopwatch), modCount });
    } catch (IOException e) {
        throw Exceptions.propagate(e);
    } finally {
        lock.writeLock().unlock();
    }
}

From source file:org.lenskit.cli.commands.Recommend.java

@Override
public void execute(Namespace opts) throws IOException, RecommenderBuildException {
    Context ctx = new Context(opts);
    LenskitRecommenderEngine engine = ctx.loader.loadEngine();

    List<Long> users = ctx.options.get("users");
    final int n = ctx.options.getInt("num_recs");

    try (LenskitRecommender rec = engine.createRecommender()) {
        ItemRecommender irec = rec.getItemRecommender();
        ItemNameDAO indao = rec.get(ItemNameDAO.class);
        if (irec == null) {
            logger.error("recommender has no item recommender");
            throw new UnsupportedOperationException("no item recommender");
        }//  w w  w  . j a  v a  2 s.  c  o  m

        logger.info("recommending for {} users", users.size());
        Stopwatch timer = Stopwatch.createStarted();
        for (long user : users) {
            ResultList recs = irec.recommendWithDetails(user, n, null, null);
            System.out.format("recommendations for user %d:%n", user);
            for (Result item : recs) {
                System.out.format("  %d", item.getId());
                if (indao != null) {
                    System.out.format(" (%s)", indao.getItemName(item.getId()));
                }
                System.out.format(": %.3f", item.getScore());
                System.out.println();
            }
        }
        timer.stop();
        logger.info("recommended for {} users in {}", users.size(), timer);
    }
}

From source file:org.glowroot.agent.it.harness.impl.TraceCollector.java

Trace getPartialTrace(int timeout, TimeUnit unit) throws InterruptedException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    while (stopwatch.elapsed(unit) < timeout) {
        for (Trace trace : traces) {
            if (trace.getHeader().getPartial()) {
                return trace;
            }/*from  ww  w  .j  av  a2s .  c o  m*/
        }
        MILLISECONDS.sleep(10);
    }
    if (traces.isEmpty()) {
        throw new IllegalStateException("No trace was collected");
    } else {
        throw new IllegalStateException("Trace was collected but is not partial");
    }
}

From source file:com.facebook.buck.parser.cache.impl.HybridCacheStorage.java

@Override
public void storeBuildFileManifest(HashCode weakFingerprint, HashCode strongFingerprint,
        byte[] serializedBuildFileManifest) throws IOException, InterruptedException {
    Stopwatch timer = null;//  w  w w .ja  v  a 2  s. c o m
    if (LOG.isLoggable(Level.FINE)) {
        timer = Stopwatch.createStarted();
    }

    // TODO(buck_team): Both stores can be done in parallel. The remote store is already done in
    // parallel
    // in the client, so the remote store is immediate return.
    // The local store is very cheap operation and we don't expect to do this often - store will
    // happen only once and the reads will be dominant.
    // Measure the effect of the store and optimize if needed.
    try {
        IOException firstException = null;
        try {
            localCacheStorage.storeBuildFileManifest(weakFingerprint, strongFingerprint,
                    serializedBuildFileManifest);
        } catch (IOException e) {
            firstException = e;
        }

        IOException secondException = null;
        try {
            remoteCacheStorage.storeBuildFileManifest(weakFingerprint, strongFingerprint,
                    serializedBuildFileManifest);
        } catch (IOException e) {
            secondException = e;
        }

        if (firstException != null && secondException != null) {
            firstException.addSuppressed(secondException);
            throw firstException;
        }

        if (firstException != null) {
            throw firstException;
        }

        if (secondException != null) {
            throw secondException;
        }
    } finally {
        if (timer != null) {
            LOG.debug("Time to complete HybridCacheStorage.storeBuildFileManifest method: %d ns.",
                    timer.stop().elapsed(TimeUnit.NANOSECONDS));
        }
    }
}

From source file:org.grouplens.lenskit.cli.Recommend.java

@Override
public void execute() throws IOException, RecommenderBuildException {
    LenskitRecommenderEngine engine = loadEngine();

    List<Long> users = options.get("users");
    final int n = options.getInt("num_recs");

    LenskitRecommender rec = engine.createRecommender();
    ItemRecommender irec = rec.getItemRecommender();
    if (irec == null) {
        logger.error("recommender has no item recommender");
        throw new UnsupportedOperationException("no item recommender");
    }/*from  w  w  w .j  ava 2 s  .  co m*/

    logger.info("recommending for {} users", users.size());
    Symbol pchan = getPrintChannel();
    Stopwatch timer = Stopwatch.createStarted();
    for (long user : users) {
        List<ScoredId> recs = irec.recommend(user, n);
        System.out.format("recommendations for user %d:\n", user);
        for (ScoredId item : recs) {
            System.out.format("  %d: %.3f", item.getId(), item.getScore());
            if (pchan != null && item.hasUnboxedChannel(pchan)) {
                System.out.format(" (%f)", item.getUnboxedChannelValue(pchan));
            }
            System.out.println();
        }
    }
    timer.stop();
    logger.info("recommended for {} users in {}", users.size(), timer);
}

From source file:com.google.cloud.genomics.gatk.htsjdk.GA4GHSamRecordIterator.java

/** Re-queries the API for the next interval */
ReadIteratorResource<Read, ReadGroupSet, Reference> queryNextInterval() {
    Stopwatch w = Stopwatch.createStarted();
    if (!isAtEnd()) {
        intervalIndex++;//  w w w  .j av  a  2s . c  o  m
    }
    if (isAtEnd()) {
        return null;
    }
    ReadIteratorResource<Read, ReadGroupSet, Reference> result = queryForInterval(currentInterval());
    LOG.info("Interval query took: " + w);
    startTiming();
    return result;
}