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:benchmarkio.consumer.kafka.BlockingKafkaMessageConsumer.java

@Override
public Histogram call() throws Exception {
    int messageCount = 0;

    try {/*  w  w w.j  ava  2 s . c  om*/
        final ConsumerIterator<byte[], byte[]> it = stream.iterator();
        while (it.hasNext()) {
            try {
                // Start
                final Stopwatch stopwatch = Stopwatch.createStarted();

                final byte[] message = it.next().message();

                messageCount++;

                // End
                stopwatch.stop();
                histogram.recordValue(stopwatch.elapsed(Consts.TIME_UNIT_FOR_REPORTING));
            } catch (final Exception e) {
                logger.error("Error processing message", e);
            }
        }
    } catch (final ConsumerTimeoutException e) {
        // This is by purpose, hence no error logging.
        logger.info("Consumer was terminated through timeout");
    }

    logger.info("In total consumed {} messages", messageCount);

    return histogram;
}

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

/**
 * Runs a performance test. Repeatedly executes the given job. It measuring either the time it takes for
 * many iterations, or the number of iterations it can execute in a fixed time.
 *///  w  w w  .j a v a2 s. c o  m
public static PerformanceTestResult run(PerformanceTestDescriptor options) {
    options.seal();
    long nextLogTime = (options.logInterval == null) ? Long.MAX_VALUE : options.logInterval.toMilliseconds();

    // Try to force garbage collection before the test, so it interferes less with the measurement.
    System.gc();
    System.gc();

    // Run some warm-up cycles.
    Stopwatch warmupWatch = Stopwatch.createStarted();
    int warmupCounter = 0;

    while ((options.warmup != null) ? options.warmup.isLongerThan(warmupWatch)
            : warmupCounter < options.warmupIterations) {
        if (warmupWatch.elapsed(TimeUnit.MILLISECONDS) >= nextLogTime) {
            LOG.info("Warm-up " + options.summary + " iteration=" + warmupCounter + " at "
                    + Time.makeTimeStringRounded(warmupWatch));
            nextLogTime += options.logInterval.toMilliseconds();
        }
        options.job.run();
        warmupCounter++;
    }
    warmupWatch.stop();

    // Run the actual test (for the given duration / iterations); then wait for completionLatch (if supplied).
    nextLogTime = (options.logInterval == null) ? Long.MAX_VALUE : options.logInterval.toMilliseconds();
    int counter = 0;
    Histogram histogram = new Histogram();
    List<Double> cpuSampleFractions = Lists.newLinkedList();
    Future<?> sampleCpuFuture = null;
    if (options.sampleCpuInterval != null) {
        sampleCpuFuture = PerformanceTestUtils.sampleProcessCpuTime(options.sampleCpuInterval, options.summary,
                cpuSampleFractions);
    }

    try {
        long preCpuTime = PerformanceTestUtils.getProcessCpuTime();
        Stopwatch watch = Stopwatch.createStarted();

        while ((options.duration != null) ? options.duration.isLongerThan(watch)
                : counter < options.iterations) {
            if (warmupWatch.elapsed(TimeUnit.MILLISECONDS) >= nextLogTime) {
                LOG.info(
                        options.summary + " iteration=" + counter + " at " + Time.makeTimeStringRounded(watch));
                nextLogTime += options.logInterval.toMilliseconds();
            }
            long before = watch.elapsed(TimeUnit.NANOSECONDS);
            options.job.run();
            if (options.histogram) {
                histogram.add(watch.elapsed(TimeUnit.NANOSECONDS) - before, TimeUnit.NANOSECONDS);
            }
            counter++;
        }

        if (options.completionLatch != null) {
            try {
                boolean success = options.completionLatch.await(options.completionLatchTimeout.toMilliseconds(),
                        TimeUnit.MILLISECONDS);
                if (!success) {
                    fail("Timeout waiting for completionLatch: test=" + options + "; counter=" + counter);
                }
            } catch (InterruptedException e) {
                throw Exceptions.propagate(e);
            }
        }
        watch.stop();
        long postCpuTime = PerformanceTestUtils.getProcessCpuTime();

        // Generate the results
        PerformanceTestResult result = new PerformanceTestResult();
        result.warmup = Duration.of(warmupWatch);
        result.warmupIterations = warmupCounter;
        result.duration = Duration.of(watch);
        result.iterations = counter;
        result.ratePerSecond = (((double) counter) / watch.elapsed(TimeUnit.MILLISECONDS)) * 1000;
        result.cpuTotalFraction = (watch.elapsed(TimeUnit.NANOSECONDS) > 0 && preCpuTime >= 0)
                ? ((double) postCpuTime - preCpuTime) / watch.elapsed(TimeUnit.NANOSECONDS)
                : -1;
        if (options.histogram) {
            result.histogram = histogram;
        }
        if (options.sampleCpuInterval != null) {
            result.cpuSampleFractions = cpuSampleFractions;
        }
        result.minAcceptablePerSecond = options.minAcceptablePerSecond;

        // Persist the results
        if (options.persister != null) {
            options.persister.persist(new Date(), options, result);
        }

        // Fail if we didn't meet the minimum performance requirements
        if (options.minAcceptablePerSecond != null && options.minAcceptablePerSecond > result.ratePerSecond) {
            fail("Performance too low: test=" + options + "; result=" + result);
        }

        return result;

    } finally {
        if (sampleCpuFuture != null) {
            sampleCpuFuture.cancel(true);
        }
    }
}

From source file:org.geogit.gwc.TruncateHelper.java

public static void issueTruncateTasks(Context geogit, Optional<Ref> oldRef, Optional<Ref> newRef,
        GeoServerTileLayer tileLayer, TileBreeder breeder) {

    final ObjectId oldCommit = oldRef.isPresent() ? oldRef.get().getObjectId() : ObjectId.NULL;
    final ObjectId newCommit = newRef.isPresent() ? newRef.get().getObjectId() : ObjectId.NULL;

    final String tileLayerName = tileLayer.getName();
    final String layerTreeName = tileLayer.getLayerInfo().getResource().getNativeName();

    LOGGER.debug("Computing minimal bounds geometry on layer '{}' (tree '{}') for change {}...{} ",
            tileLayerName, layerTreeName, oldCommit, newCommit);
    final Geometry minimalBounds;
    Stopwatch sw = Stopwatch.createStarted();
    try {//from   w w w . j  a v  a  2 s  . c  om
        MinimalDiffBounds geomBuildCommand = geogit.command(MinimalDiffBounds.class)
                .setOldVersion(oldCommit.toString()).setNewVersion(newCommit.toString());

        geomBuildCommand.setTreeNameFilter(layerTreeName);

        minimalBounds = geomBuildCommand.call();
        sw.stop();
        if (minimalBounds.isEmpty()) {
            LOGGER.debug("Feature tree '{}' not affected by change {}...{} (took {})", layerTreeName, oldCommit,
                    newCommit, sw);
            return;
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Minimal bounds on layer '{}' computed in {}: {}", tileLayerName, sw,
                    formattedWKT(minimalBounds));
        }
    } catch (Exception e) {
        sw.stop();
        LOGGER.error("Error computing minimal bounds for {}...{} on layer '{}' after {}", oldCommit, newCommit,
                tileLayerName, sw);
        throw Throwables.propagate(e);
    }
    final Set<String> gridSubsets = tileLayer.getGridSubsets();

    LayerInfo layerInfo = tileLayer.getLayerInfo();
    ResourceInfo resource = layerInfo.getResource();
    final CoordinateReferenceSystem nativeCrs = resource.getNativeCRS();

    for (String gridsetId : gridSubsets) {
        GridSubset gridSubset = tileLayer.getGridSubset(gridsetId);
        final CoordinateReferenceSystem gridSetCrs = getGridsetCrs(gridSubset);

        LOGGER.debug("Reprojecting geometry mask to gridset {}", gridsetId);
        Geometry geomInGridsetCrs = transformToGridsetCrs(minimalBounds, nativeCrs, gridSetCrs);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("geometry mask reprojected to gridset {}: {}", gridsetId,
                    formattedWKT(geomInGridsetCrs));
        }
        geomInGridsetCrs = bufferAndSimplifyBySizeOfSmallerTile(geomInGridsetCrs, gridSetCrs, gridSubset);
        try {
            truncate(tileLayer, gridsetId, geomInGridsetCrs, breeder);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.facebook.buck.distributed.build_slave.BuildSlaveTimingStatsTracker.java

public synchronized void startTimer(SlaveEvents event) {
    Preconditions.checkState(!watches.containsKey(event), "Stopwatch for %s has already been started.", event);
    watches.put(event, Stopwatch.createStarted());
}

From source file:com.webbfontaine.valuewebb.irms.core.RuleCallable.java

@Override
public T call() throws Exception {
    Stopwatch stopwatch = Stopwatch.createStarted();

    RuleContext ruleContext = ruleContextBuilder.createRuleContext();
    TTSourceBean ttSourceBean = sourceBeanBuilder.createSourceBean();

    T result = applyRule(criterion, ruleContext, ttSourceBean);

    stopwatch.stop();//from   ww  w. j  av  a  2  s .c  om

    LOGGER.debug("Rule: {} execution time for TT with id: {}, pds size: {} is: {}", new Object[] {
            criterion.getCode(), ttSourceBean.getTtId(), ttSourceBean.getTtNumberOfItems(), stopwatch });

    return result;
}

From source file:io.wcm.caravan.pipeline.impl.JsonPathSelector.java

@Override
public ArrayNode call(JsonNode inputData) throws PathNotFoundException {
    Stopwatch watch = Stopwatch.createStarted();

    ArrayNode arrayNode = JsonPath.using(config).parse(inputData).read(jsonPath, ArrayNode.class);

    log.debug("selected " + arrayNode.size() + " matches in " + watch.elapsed(MILLISECONDS)
            + " ms by applying jsonPath " + this.jsonPath);
    return arrayNode;
}

From source file:org.eclipse.viatra.dse.genetic.debug.GeneticDebugger.java

public GeneticDebugger(boolean isDebugEnabled, GlobalContext gc) {
    this.debug = isDebugEnabled;
    this.gc = gc;
    stopwatch = Stopwatch.createStarted();
}

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

public static void preShutdownCheck(Collection<Thread> preExistingThreads) throws InterruptedException {
    // give the test 5 seconds to shutdown any threads they may have created, e.g. give tomcat
    // time to shutdown when testing tomcat plugin
    Stopwatch stopwatch = Stopwatch.createStarted();
    List<Thread> nonPreExistingThreads;
    List<Thread> rogueThreads;
    do {//from   w  w  w . jav a 2s .com
        nonPreExistingThreads = getNonPreExistingThreads(preExistingThreads);
        rogueThreads = Lists.newArrayList();
        for (Thread thread : nonPreExistingThreads) {
            if (isRogueThread(thread)) {
                rogueThreads.add(thread);
            }
        }
        // check total number of threads to make sure Glowroot is not creating too many
        //
        // currently, the seven threads are:
        //
        // Glowroot-Background-0
        // Glowroot-Background-1
        // H2 Log Writer GLOWROOT
        // H2 File Lock Watchdog <lock db file>
        // Glowroot-Http-Boss
        // Glowroot-Http-Worker-0
        // Generate Seed
        if (rogueThreads.isEmpty() && nonPreExistingThreads.size() <= 7) {
            // success
            return;
        }
        // wait a few milliseconds before trying again
        Thread.sleep(10);
    } while (stopwatch.elapsed(SECONDS) < 5);
    // failure
    if (!rogueThreads.isEmpty()) {
        throw new RogueThreadsException(rogueThreads);
    } else {
        throw new TooManyThreadsException(nonPreExistingThreads);
    }
}

From source file:net.thangbui.cql_exporter.SchemaExporter.java

public void run() throws Exception {
    Stopwatch stopwatch = Stopwatch.createStarted();

    KeyspaceMetadata keyspace = validate();

    System.out.println("All good!");
    System.out.println("Start exporting...");

    long freeMemory = Runtime.getRuntime().freeMemory();
    FETCH_SIZE = Math.min(NO_OF_ENTRY_BOUND, (int) (freeMemory / 1000));
    if (Main.VERBOSE) {
        System.out.println("Free memory: " + freeMemory / 1024 / 1024 + " mb");
        System.out.println("Fetch size is set to: " + FETCH_SIZE);
    }//ww w .  j a va2  s  . c o m

    if (Strings.isNullOrEmpty(tableName)) {
        extractKeyspace(keyspace);
    } else {
        extractOnlyOneTable(keyspace);
    }

    stopwatch.stop();
    System.out.printf("Export completed after %s s!" + Main.LINE_SEPARATOR,
            (float) stopwatch.elapsed(TimeUnit.MILLISECONDS) / 1000);
    System.out.println("Exited.");
}

From source file:bear.main.CompileManager.java

public synchronized CompilationResult compileWithAll() {
    logger.info("compiling...");

    Stopwatch sw = Stopwatch.createStarted();

    if (lastCompilationResult != null && System.currentTimeMillis() - lastCompilationResult.timestamp() < 300) {
        logger.debug("cancelled compilation, up to date");
    } else {//from www.  j a  v  a  2 s  .co  m
        lastCompilationResult = groovyCompiler.compile(dependenciesCL.or(getClass().getClassLoader()));
    }

    logger.info("compilation finished in {}s", LangUtils.millisToSec(sw.elapsed(TimeUnit.MILLISECONDS)));

    return lastCompilationResult;
}