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.palantir.atlasdb.keyvalue.impl.ProfilingKeyValueService.java

private static void logCellsAndSize(String method, String tableName, int numCells, long sizeInBytes,
        Stopwatch stopwatch) {
    log.trace("Call to KVS.{} on table {} for {} cells of overall size {} bytes took {} ms.", method, tableName,
            numCells, sizeInBytes, stopwatch.elapsed(TimeUnit.MILLISECONDS));
}

From source file:processing.BM25Calculator.java

private static List<Map<Integer, Double>> startBM25CreationForTagPrediction(BookmarkReader reader,
        int sampleSize, boolean userBased, boolean resBased, int beta) {
    timeString = "";
    int size = reader.getUserLines().size();
    int trainSize = size - sampleSize;
    Stopwatch timer = new Stopwatch();
    timer.start();/*ww  w.  j  av a 2 s.  c  om*/
    BM25Calculator calculator = new BM25Calculator(reader, trainSize, true, userBased, resBased, beta);
    timer.stop();
    long trainingTime = timer.elapsed(TimeUnit.MILLISECONDS);

    List<Map<Integer, Double>> results = new ArrayList<Map<Integer, Double>>();
    timer = new Stopwatch();
    timer.start();
    for (int i = trainSize; i < size; i++) {
        UserData data = reader.getUserLines().get(i);
        Map<Integer, Double> map = null;
        map = calculator.getRankedTagList(data.getUserID(), data.getWikiID(), true);
        results.add(map);
        //System.out.println(data.getTags() + "|" + map.keySet());
    }
    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 / (double) sampleSize) + "\n";
    timeString += ("Total time: " + (trainingTime + testTime) + "\n");

    return results;
}

From source file:org.apache.drill.exec.store.schedule.BlockMapBuilder.java

/**
 * Builds a mapping of Drillbit endpoints to hostnames
 *//*from  w ww.  jav a 2 s . co m*/
private static ImmutableMap<String, DrillbitEndpoint> buildEndpointMap(Collection<DrillbitEndpoint> endpoints) {
    Stopwatch watch = new Stopwatch();
    watch.start();
    HashMap<String, DrillbitEndpoint> endpointMap = Maps.newHashMap();
    for (DrillbitEndpoint d : endpoints) {
        String hostName = d.getAddress();
        endpointMap.put(hostName, d);
    }
    watch.stop();
    logger.debug("Took {} ms to build endpoint map", watch.elapsed(TimeUnit.MILLISECONDS));
    return ImmutableMap.copyOf(endpointMap);
}

From source file:com.google.cloud.examples.nio.CountBytes.java

/**
 * Print the length of the indicated file.
 *
 * <p>This uses the normal Java NIO Api, so it can take advantage of any installed
 * NIO Filesystem provider without any extra effort.
 *//*from  w w  w .  ja v a2s.c  o  m*/
private static void countFile(String fname) {
    // large buffers pay off
    final int bufSize = 50 * 1024 * 1024;
    try {
        Path path = Paths.get(new URI(fname));
        long size = Files.size(path);
        System.out.println(fname + ": " + size + " bytes.");
        ByteBuffer buf = ByteBuffer.allocate(bufSize);
        System.out.println("Reading the whole file...");
        Stopwatch sw = Stopwatch.createStarted();
        try (SeekableByteChannel chan = Files.newByteChannel(path)) {
            long total = 0;
            int readCalls = 0;
            MessageDigest md = MessageDigest.getInstance("MD5");
            while (chan.read(buf) > 0) {
                readCalls++;
                md.update(buf.array(), 0, buf.position());
                total += buf.position();
                buf.flip();
            }
            readCalls++; // We must count the last call
            long elapsed = sw.elapsed(TimeUnit.SECONDS);
            System.out.println("Read all " + total + " bytes in " + elapsed + "s. " + "(" + readCalls
                    + " calls to chan.read)");
            String hex = String.valueOf(BaseEncoding.base16().encode(md.digest()));
            System.out.println("The MD5 is: 0x" + hex);
            if (total != size) {
                System.out.println("Wait, this doesn't match! We saw " + total + " bytes, "
                        + "yet the file size is listed at " + size + " bytes.");
            }
        }
    } catch (Exception ex) {
        System.out.println(fname + ": " + ex.toString());
    }
}

From source file:edu.illinois.keshmesh.detector.Main.java

public static BugInstances initAndPerformAnalysis(IJavaProject javaProject, Reporter reporter,
        ConfigurationOptions configurationOptions) throws WALAInitializationException {
    BugInstances bugInstances = new BugInstances();
    int objectSensitivityLevel = configurationOptions.getObjectSensitivityLevel();
    reporter.report(new KeyValuePair("OBJECT_SENSITIVITY_LEVEL", String.valueOf(objectSensitivityLevel)));
    BasicAnalysisData basicAnalysisData = initBytecodeAnalysis(javaProject, reporter, configurationOptions);
    if (configurationOptions.shouldDumpCallGraph()) {
        dumpCallGraph(basicAnalysisData.callGraph);
    }/*from  w ww .  j av  a2s.  c om*/
    Iterator<BugPattern> bugPatternsIterator = BugPatterns.iterator();
    while (bugPatternsIterator.hasNext()) {
        BugPattern bugPattern = bugPatternsIterator.next();
        BugPatternDetector bugPatternDetector = bugPattern.createBugPatternDetector();
        Stopwatch stopWatch = Stopwatch.createStarted();
        BugInstances instancesOfCurrentBugPattern = bugPatternDetector.performAnalysis(javaProject,
                basicAnalysisData);
        stopWatch.stop();
        reporter.report(
                new KeyValuePair("BUG_PATTERN_" + bugPattern.getName() + "_DETECTION_TIME_IN_MILLISECONDS",
                        String.valueOf(stopWatch.elapsed(TimeUnit.MILLISECONDS))));
        bugInstances.addAll(instancesOfCurrentBugPattern);
        reporter.report(new KeyValuePair("NUMBER_OF_INSTANCES_OF_BUG_PATTERN_" + bugPattern.getName(),
                String.valueOf(instancesOfCurrentBugPattern.size())));
    }
    reporter.close();
    return bugInstances;
}

From source file:com.hortonworks.streamline.common.util.ParallelStreamUtil.java

public static <T> T execute(Supplier<T> supplier, Executor executor) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    LOG.debug("execute start");

    try {/*from w  w w  .j  a va  2 s . c om*/
        CompletableFuture<T> resultFuture = CompletableFuture.supplyAsync(supplier, executor);
        return resultFuture.get();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (ExecutionException e) {
        handleExecutionException(e);
        // shouldn't reach here
        throw new IllegalStateException("Shouldn't reach here");
    } finally {
        LOG.debug("execute complete - elapsed: {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
        stopwatch.stop();
    }
}

From source file:io.prestosql.verifier.VerifyCommand.java

@VisibleForTesting
static List<QueryPair> rewriteQueries(SqlParser parser, VerifierConfig config, List<QueryPair> queries) {
    QueryRewriter testRewriter = new QueryRewriter(parser, config.getTestGateway(),
            config.getShadowTestTablePrefix(), Optional.ofNullable(config.getTestCatalogOverride()),
            Optional.ofNullable(config.getTestSchemaOverride()),
            Optional.ofNullable(config.getTestUsernameOverride()),
            Optional.ofNullable(config.getTestPasswordOverride()), config.getDoublePrecision(),
            config.getTestTimeout());/*from  w w  w .ja  v a  2  s.  c o  m*/

    QueryRewriter controlRewriter = new QueryRewriter(parser, config.getControlGateway(),
            config.getShadowControlTablePrefix(), Optional.ofNullable(config.getControlCatalogOverride()),
            Optional.ofNullable(config.getControlSchemaOverride()),
            Optional.ofNullable(config.getControlUsernameOverride()),
            Optional.ofNullable(config.getControlPasswordOverride()), config.getDoublePrecision(),
            config.getControlTimeout());

    LOG.info("Rewriting %s queries using %s threads", queries.size(), config.getThreadCount());
    ExecutorService executor = newFixedThreadPool(config.getThreadCount());
    CompletionService<Optional<QueryPair>> completionService = new ExecutorCompletionService<>(executor);

    List<QueryPair> rewritten = new ArrayList<>();
    for (QueryPair pair : queries) {
        completionService.submit(() -> {
            try {
                return Optional.of(
                        new QueryPair(pair.getSuite(), pair.getName(), testRewriter.shadowQuery(pair.getTest()),
                                controlRewriter.shadowQuery(pair.getControl())));
            } catch (QueryRewriteException | SQLException e) {
                if (!config.isQuiet()) {
                    LOG.warn(e, "Failed to rewrite %s for shadowing. Skipping.", pair.getName());
                }
                return Optional.empty();
            }
        });
    }

    executor.shutdown();

    try {
        Stopwatch stopwatch = Stopwatch.createStarted();
        for (int n = 1; n <= queries.size(); n++) {
            completionService.take().get().ifPresent(rewritten::add);

            if (!config.isQuiet() && (stopwatch.elapsed(MINUTES) > 0)) {
                stopwatch.reset().start();
                LOG.info("Rewrite progress: %s valid, %s skipped, %.2f%% done", rewritten.size(),
                        n - rewritten.size(), (((double) n) / queries.size()) * 100);
            }
        }
    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException("Query rewriting failed", e);
    }

    LOG.info("Rewrote %s queries into %s queries", queries.size(), rewritten.size());
    return rewritten;
}

From source file:com.hortonworks.streamline.common.util.ParallelStreamUtil.java

public static void runAsync(Callable<Void> callable, Executor executor) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    LOG.debug("runAsync start");
    CompletableFuture<Void> res = CompletableFuture.supplyAsync(() -> {
        try {/*from   w  ww .  ja  v  a2s  .c  om*/
            return callable.call();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }, executor);

    res.whenComplete((r, th) -> {
        // LOG any exceptions
        if (th != null) {
            LOG.error("Got exception while running async task", th.getCause());
        }
        LOG.debug("runAsync complete - elapsed: {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
        stopwatch.stop();
    });
}

From source file:processing.BLLCalculator.java

private static List<Map<Integer, Double>> startActCreation(BookmarkReader reader, int sampleSize,
        boolean sorting, boolean userBased, boolean resBased, double dVal, int beta, CalculationType cType,
        Double lambda) {/*from  ww w  .  j av a  2 s.c  om*/
    int size = reader.getBookmarks().size();
    int trainSize = size - sampleSize;

    Stopwatch timer = new Stopwatch();
    timer.start();
    BLLCalculator calculator = new BLLCalculator(reader, trainSize, dVal, beta, userBased, resBased, cType,
            lambda);
    timer.stop();
    long trainingTime = timer.elapsed(TimeUnit.MILLISECONDS);
    List<Map<Integer, Double>> results = new ArrayList<Map<Integer, Double>>();
    if (trainSize == size) {
        trainSize = 0;
    }

    timer.reset();
    timer.start();
    for (int i = trainSize; i < size; i++) { // the test-set
        Bookmark data = reader.getBookmarks().get(i);
        Map<Integer, Double> map = calculator.getRankedTagList(data.getUserID(), data.getResourceID(), sorting,
                cType);
        results.add(map);
    }
    timer.stop();
    long testTime = timer.elapsed(TimeUnit.MILLISECONDS);

    timeString = PerformanceMeasurement.addTimeMeasurement(timeString, true, trainingTime, testTime,
            sampleSize);
    return results;
}

From source file:info_teorija_1.Encode.java

public static void encode(int wordLength, File in, File out) throws IOException {
    Stopwatch total = Stopwatch.createStarted();
    Stopwatch time = Stopwatch.createStarted();

    /* create input/output buffered file streams */
    FileInputStream inputStream = new FileInputStream(in);
    BufferedInputStream src = new BufferedInputStream(inputStream);
    input = new BitInput(src);

    OutputStream dst = new FileOutputStream(out);
    BufferedOutputStream outputStream = new BufferedOutputStream(dst);
    output = new BitOutput(outputStream);

    getFrequenciesAndWriteRemainder(in, wordLength);
    System.out.println("getFrequancies " + time.elapsed(TimeUnit.MILLISECONDS));

    time.stop();/*  w ww. j av a  2  s  .  c om*/
    time = Stopwatch.createStarted();

    // build tree
    HuffmanTree tree = HuffmanCode.buildTree(byteFreqs);
    System.out.println("BuildTree " + time.elapsed(TimeUnit.MILLISECONDS));

    time.stop();
    time = Stopwatch.createStarted();

    // generateCodes and fill huffmanTable
    HuffmanCode.genCodes(tree, new StringBuffer());
    System.out.println("genCodes " + time.elapsed(TimeUnit.MILLISECONDS));

    Encode.wordLength = wordLength;

    time.stop();
    time = Stopwatch.createStarted();

    output.writeUnsignedInt(4, wordLength - 1);
    output.writeUnsignedLong(32, bytesLength);

    encodeTree(tree);
    System.out.println("encodeTree " + time.elapsed(TimeUnit.MILLISECONDS));
    time.stop();
    time = Stopwatch.createStarted();

    encodeFile();

    System.out.println("encodeFile " + time.elapsed(TimeUnit.MILLISECONDS));
    time.stop();

    outputStream.close();
    inputStream.close();
    System.out.println("TOTAL: " + total.elapsed(TimeUnit.MILLISECONDS));
    total.stop();
}