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:ec.jwsacruncher.App.java

private static void process(FileWorkspace ws, WorkspaceItem item, SaProcessing processing,
        EstimationPolicyType policy, int bundleSize) throws IOException {
    Stopwatch stopwatch = Stopwatch.createStarted();

    System.out.println("Refreshing data");
    processing.refresh(policy, false);/* ww  w.  jav a2s  . c  o m*/
    SaBatchInformation info = new SaBatchInformation(processing.size() > bundleSize ? bundleSize : 0);
    info.setName(item.getId());
    info.setItems(processing);
    SaBatchProcessor processor = new SaBatchProcessor(info, new ConsoleFeedback());
    processor.process();

    System.out.println("Saving new processing...");
    FileRepository.storeSaProcessing(ws, item, processing);

    System.out.println("Processing time: " + stopwatch.elapsed(TimeUnit.SECONDS) + "s");
}

From source file:org.apache.drill.common.util.PathScanner.java

/**
 * @param  scanPackages  note:  not currently used
 *///from w ww  . j  a v a  2 s .  co  m
public static <T> Set<Class<? extends T>> scanForImplementations(final Class<T> baseClass,
        final List<String> scanPackages) {
    final Stopwatch w = new Stopwatch().start();
    try {
        synchronized (SYNC) {
            final Set<Class<? extends T>> classes = getReflections().getSubTypesOf(baseClass);
            for (Iterator<Class<? extends T>> i = classes.iterator(); i.hasNext();) {
                final Class<? extends T> c = i.next();
                assert baseClass.isAssignableFrom(c);
                if (Modifier.isAbstract(c.getModifiers())) {
                    i.remove();
                }
            }
            return classes;
        }
    } finally {
        logger.debug("Implementations scanning took {} ms for {}.", w.elapsed(TimeUnit.MILLISECONDS),
                baseClass); // no .getName(), so it has "class "/"interface "
    }
}

From source file:com.spotify.heroic.metric.ResultGroups.java

public static Collector<ResultGroups, ResultGroups> collect(final QueryTrace.Identifier what) {
    final Stopwatch w = Stopwatch.createStarted();

    return results -> {
        final ImmutableList.Builder<ResultGroup> groups = ImmutableList.builder();
        final ImmutableList.Builder<RequestError> errors = ImmutableList.builder();
        final ImmutableList.Builder<QueryTrace> traces = ImmutableList.builder();

        Statistics statistics = Statistics.empty();

        for (final ResultGroups r : results) {
            groups.addAll(r.groups);//from   w w  w . j  av  a2 s .  c  om
            errors.addAll(r.errors);
            traces.add(r.trace);
            statistics = statistics.merge(r.statistics);
        }

        return new ResultGroups(groups.build(), errors.build(), statistics,
                new QueryTrace(what, w.elapsed(TimeUnit.NANOSECONDS), traces.build()));
    };
}

From source file:net.sf.lucis.core.LucisQuery.java

public static <T> LucisQuery<Item<T>> first(final Query query, final Filter filter, final Sort sort,
        final DocMapper<T> mapper, final Highlight highlight) {
    return new LucisQuery<Item<T>>() {
        public Item<T> perform(final LucisSearcher searcher) {
            Stopwatch w = Stopwatch.createStarted();
            Query rewritten = searcher.rewrite(query);
            TopDocs docs = getTopDocs(searcher, query, filter, sort, 1);
            if (docs.totalHits > 0) {
                ScoreDoc sd = docs.scoreDocs[0];
                Document doc = searcher.doc(sd.doc);
                HighlightedQuery highlighted = MoreObjects.firstNonNull(highlight, Highlight.no())
                        .highlight(rewritten);
                float score = sd.score;
                T item = mapper.map(sd.doc, score, doc, highlighted.getFragments(doc));
                return new Item<T>(docs.totalHits, score, w.elapsed(TimeUnit.MILLISECONDS), item);
            } else {
                return new Item<T>(docs.totalHits, 0.0f, w.elapsed(TimeUnit.MILLISECONDS), null);
            }/*from  w ww .java 2 s .c om*/
        }
    };
}

From source file:edu.mit.streamjit.test.Benchmarker.java

private static Result run(Benchmark benchmark, Dataset input, StreamCompiler compiler) {
    long compileMillis, runMillis;
    VerifyingOutputBufferFactory verifier = null;
    OutputCounter counter;//from   w  w  w.  j a  v a 2s . c om
    if (input.output() != null)
        counter = verifier = new VerifyingOutputBufferFactory(input.output());
    else
        counter = new CountingOutputBufferFactory();
    try {
        CompileThread ct = new CompileThread(compiler, benchmark, input, counter);
        Stopwatch stopwatch = Stopwatch.createStarted();
        ct.start();
        ct.join(TimeUnit.MILLISECONDS.convert(COMPILE_TIMEOUT_DURATION, COMPILE_TIMEOUT_UNIT));
        compileMillis = stopwatch.elapsed(TimeUnit.MILLISECONDS);
        if (ct.isAlive())
            throw new TimeoutException();
        if (ct.throwable != null)
            throw ct.throwable;

        CompiledStream stream = ct.stream;
        stream.awaitDrained(RUN_TIMEOUT_DURATION, RUN_TIMEOUT_UNIT);
        stopwatch.stop();
        runMillis = stopwatch.elapsed(TimeUnit.MILLISECONDS) - compileMillis;
    } catch (TimeoutException ex) {
        return Result.timeout(benchmark, input, compiler);
    } catch (InterruptedException ex) {
        return Result.exception(benchmark, input, compiler, ex);
    } catch (Throwable t) {
        return Result.exception(benchmark, input, compiler, t);
    }
    long outputs = counter.getCount();
    if (verifier != null) {
        verifier.buffer.finish();
        if (!verifier.buffer.correct())
            return Result.wrongOutput(benchmark, input, compiler, compileMillis, runMillis,
                    verifier.buffer.extents, verifier.buffer.missingOutput, verifier.buffer.excessOutput);
    }
    return Result.ok(benchmark, input, compiler, compileMillis, runMillis, outputs);
}

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

public static void postShutdownCheck(Collection<Thread> preExistingThreads) throws InterruptedException {
    // give it 5 seconds to shutdown threads
    Stopwatch stopwatch = Stopwatch.createStarted();
    List<Thread> rogueThreads;
    do {/*from  w  ww. j a  va2s .  c o  m*/
        rogueThreads = getNonPreExistingThreads(preExistingThreads);
        if (rogueThreads.isEmpty()) {
            // success
            return;
        }
        // make an exception for H2's Generate Seed thread since it can take a bit of time to
        // complete on some systems (e.g. travis-ci), but is otherwise harmless
        if (rogueThreads.size() == 1 && rogueThreads.get(0).getName().equals(getGenerateSeedThreadName())) {
            // success
            return;
        }
        // wait a few milliseconds before trying again
        Thread.sleep(10);
    } while (stopwatch.elapsed(SECONDS) < 5);
    // failure
    throw new RogueThreadsException(rogueThreads);
}

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

/**
 * Print the length and MD5 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 a 2  s . co  m*/
private static void countFile(String fname) throws Exception {
    // large buffers pay off
    final int bufSize = 50 * 1024 * 1024;
    Queue<Future<WorkUnit>> work = new ArrayDeque<>();
    Path path = Paths.get(new URI(fname));
    long size = Files.size(path);
    System.out.println(fname + ": " + size + " bytes.");
    int nThreads = (int) Math.ceil(size / (double) bufSize);
    if (nThreads > 4)
        nThreads = 4;
    System.out.println("Reading the whole file using " + nThreads + " threads...");
    Stopwatch sw = Stopwatch.createStarted();
    long total = 0;
    MessageDigest md = MessageDigest.getInstance("MD5");

    ExecutorService exec = Executors.newFixedThreadPool(nThreads);
    int blockIndex;
    for (blockIndex = 0; blockIndex < nThreads; blockIndex++) {
        work.add(exec.submit(new WorkUnit(Files.newByteChannel(path), bufSize, blockIndex)));
    }
    while (!work.isEmpty()) {
        WorkUnit full = work.remove().get();
        md.update(full.buf.array(), 0, full.buf.position());
        total += full.buf.position();
        if (full.buf.hasRemaining()) {
            full.close();
        } else {
            work.add(exec.submit(full.resetForIndex(blockIndex++)));
        }
    }
    exec.shutdown();

    long elapsed = sw.elapsed(TimeUnit.SECONDS);
    System.out.println("Read all " + total + " bytes in " + elapsed + "s. ");
    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.");
    }
}

From source file:org.glowroot.agent.it.harness.Threads.java

public static void postShutdownCheck(Collection<Thread> preExistingThreads) throws InterruptedException {
    // give it 5 seconds to shutdown threads
    Stopwatch stopwatch = Stopwatch.createStarted();
    List<Thread> rogueThreads;
    do {/*w ww .j a v  a 2s  . c o  m*/
        rogueThreads = getNonPreExistingThreads(preExistingThreads);
        if (rogueThreads.isEmpty()) {
            // success
            return;
        }
        // make an exception for H2's Generate Seed thread since it can take a bit of time to
        // complete on some systems (e.g. travis-ci), but is otherwise harmless
        if (rogueThreads.size() == 1 && rogueThreads.get(0).getName().equals(getGenerateSeedThreadName())) {
            // success
            return;
        }
        // wait a few milliseconds before trying again
        MILLISECONDS.sleep(10);
    } while (stopwatch.elapsed(SECONDS) < 10);
    // failure
    throw new RogueThreadsException(rogueThreads);
}

From source file:info_teorija_1.Decode.java

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

    FileInputStream src = new FileInputStream(in);
    BufferedInputStream inputStream = new BufferedInputStream(src);
    input = new BitInput(inputStream);

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

    int remainderLength = input.readUnsignedInt(4);
    int remainder = 0;

    if (remainderLength != 0) {
        remainder = input.readUnsignedInt(15);
    } else {/*from   w  w w.  j av  a 2  s .  c  o m*/
        input.readUnsignedInt(15);
    }

    wordLength = input.readUnsignedInt(4) + 1;
    length = input.readUnsignedLong(32);

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

    while (true) {
        if (totalHuffmanLeafs != 0 && totalHuffmanLeafs == currentHuffmanLeafs) {
            break;
        }
        decodeTree();
    }
    System.out.println("decodeTree() " + time.elapsed(TimeUnit.MILLISECONDS));

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

    HuffmanCode.genCodes(tree, new StringBuffer());
    System.out.println("genCodes() " + time.elapsed(TimeUnit.MILLISECONDS));

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

    decodeFile();
    System.out.println("decodeFile() " + time.elapsed(TimeUnit.MILLISECONDS));
    if (remainderLength != 0)
        output.writeUnsignedInt(remainderLength, remainder);

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

}

From source file:org.apache.jackrabbit.oak.run.DataStoreCheckCommand.java

private static void checkConsistency(File ids, File refs, File missing) throws IOException {
    System.out.println("Starting consistency check");
    Stopwatch watch = createStarted();

    FileLineDifferenceIterator iter = new FileLineDifferenceIterator(ids, refs, new Function<String, String>() {
        @Nullable//from  ww w  . jav  a  2 s.  com
        @Override
        public String apply(@Nullable String input) {
            if (input != null) {
                return input.split(DELIM)[0];
            }
            return "";
        }
    });
    long candidates = writeStrings(iter, missing, true);

    System.out.println("Consistency check found " + candidates + " missing blobs");
    if (candidates > 0) {
        System.out.println("Consistency check failure for the data store");
    }
    System.out.println("Finished in " + watch.elapsed(TimeUnit.SECONDS) + " seconds");
}