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.gerrit.server.index.account.AllAccountsIndexer.java

private SiteIndexer.Result reindexAccounts(AccountIndex index, List<Account.Id> ids, ProgressMonitor progress) {
    progress.beginTask("Reindexing accounts", ids.size());
    List<ListenableFuture<?>> futures = new ArrayList<>(ids.size());
    AtomicBoolean ok = new AtomicBoolean(true);
    AtomicInteger done = new AtomicInteger();
    AtomicInteger failed = new AtomicInteger();
    Stopwatch sw = Stopwatch.createStarted();
    for (Account.Id id : ids) {
        String desc = "account " + id;
        ListenableFuture<?> future = executor.submit(() -> {
            try {
                accountCache.evict(id);/*from  w  ww  . ja va 2 s. com*/
                index.replace(accountCache.get(id));
                verboseWriter.println("Reindexed " + desc);
                done.incrementAndGet();
            } catch (Exception e) {
                failed.incrementAndGet();
                throw e;
            }
            return null;
        });
        addErrorListener(future, desc, progress, ok);
        futures.add(future);
    }

    try {
        Futures.successfulAsList(futures).get();
    } catch (ExecutionException | InterruptedException e) {
        log.error("Error waiting on account futures", e);
        return new SiteIndexer.Result(sw, false, 0, 0);
    }

    progress.endTask();
    return new SiteIndexer.Result(sw, ok.get(), done.get(), failed.get());
}

From source file:com.isotrol.impe3.pms.core.impl.AbstractStateLoaderComponent.java

public final T loadOnline(UUID envId) {
    final Stopwatch w = Stopwatch.createStarted();
    T value = getLoader().load(getEdition(envId));
    online.add(w.elapsed(TimeUnit.MILLISECONDS));
    return value;
}

From source file:com.persinity.ndt.controller.step.NdtInstallAndEnable.java

@Override
protected void work() {
    log.info("Installing NDT at {}, {}, {}, {}", srcAppDb, srcNdtDb, dstNdtDb, dstAppDb);
    final Stopwatch stTotal = Stopwatch.createStarted();

    view.logNdtMessage(format(//from  w ww. j  av  a 2  s  .  c  om
            "Installing NDT at Source DB \"{}\", Source Staging \"{}\",\nDestination Staging \"{}\" and Destination DB \"{}\"",
            srcAppDb.getUserName(), srcNdtDb.getUserName(), dstNdtDb.getUserName(), dstAppDb.getUserName()));
    view.setProgress(PROGRESS_ON);

    // TODO define in parallel steps to speed up setup.

    log.info("Mounting clog agent on {}...", srcNdtDb);
    final DirectedEdge<ClogAgent<Function<RelDb, RelDb>>, Stopwatch> srcClogAgentRes = timeOf(
            new Function<Void, ClogAgent<Function<RelDb, RelDb>>>() {
                @Override
                public ClogAgent<Function<RelDb, RelDb>> apply(final Void arg) {
                    final ClogAgent<Function<RelDb, RelDb>> srcClogAgent = dbAgentExecutor
                            .clogAgentInstallMount(srcDrivenDbAgentFactory, srcNdtDb);
                    srcNdtDb.commit();
                    return srcClogAgent;
                }
            }, null);
    log.info("Mounted clog agent for {}", srcClogAgentRes.dst());

    log.info("Mounting clog agent on {}...", dstNdtDb);
    final DirectedEdge<ClogAgent<Function<RelDb, RelDb>>, Stopwatch> dstClogAgentRes = timeOf(
            new Function<Void, ClogAgent<Function<RelDb, RelDb>>>() {
                @Override
                public ClogAgent<Function<RelDb, RelDb>> apply(final Void arg) {
                    final ClogAgent<Function<RelDb, RelDb>> dstClogAgent = dbAgentExecutor
                            .clogAgentInstallMount(srcDrivenDbAgentFactory, dstNdtDb);
                    dstNdtDb.commit();
                    return dstClogAgent;
                }
            }, null);
    log.info("Mounted clog agent for {}", dstClogAgentRes.dst());

    log.info("Mounting cdc agent on {} -> {}...", srcAppDb, srcNdtDb);
    final DirectedEdge<CdcAgent<Function<RelDb, RelDb>>, Stopwatch> cdcAgentRes = timeOf(
            new Function<Void, CdcAgent<Function<RelDb, RelDb>>>() {
                @Override
                public CdcAgent<Function<RelDb, RelDb>> apply(final Void arg) {
                    final CdcAgent<Function<RelDb, RelDb>> cdcAgent = dbAgentExecutor
                            .cdcAgentInstallMount(srcDrivenDbAgentFactory, srcAppDb, srcNdtDb);
                    srcAppDb.commit();
                    srcNdtDb.commit();
                    return cdcAgent;
                }
            }, null);
    log.info("Mounted cdc agent for {}", cdcAgentRes.dst());

    log.info("Mounting schema agent on {} -> {}...", dstNdtDb, dstAppDb);
    final DirectedEdge<SchemaAgent<Function<RelDb, RelDb>>, Stopwatch> dstSchemaAgentRes = timeOf(
            new Function<Void, SchemaAgent<Function<RelDb, RelDb>>>() {
                @Override
                public SchemaAgent<Function<RelDb, RelDb>> apply(final Void arg) {
                    final SchemaAgent<Function<RelDb, RelDb>> dstSchemaAgent = dbAgentExecutor
                            .schemaAgentInstallMount(dstDrivenDbAgentFactory, dstNdtDb, dstAppDb);
                    dstNdtDb.commit();
                    dstAppDb.commit();
                    return dstSchemaAgent;
                }
            }, null);
    log.info("Mounted schema agent for {}", dstSchemaAgentRes.dst());

    getCtx().put(AgentContext.class, new AgentContext(srcClogAgentRes.src(), dstClogAgentRes.src(),
            cdcAgentRes.src(), dstSchemaAgentRes.src()));

    dbAgentExecutor.trlogCleanup(srcClogAgentRes.src(), srcNdtDb);
    srcNdtDb.commit();

    log.info("Warming up schemas...");
    final Stopwatch schemasTime = timeOf(new Function<Void, Void>() {
        @Override
        public Void apply(final Void arg) {
            warmUpCache(srcAppDb.metaInfo(), SKIP_WARMUP_FKS);
            warmUpCache(dstAppDb.metaInfo(), WARMUP_FKS);
            warmUpCache(srcNdtDb.metaInfo(), SKIP_WARMUP_FKS);
            warmUpCache(dstNdtDb.metaInfo(), SKIP_WARMUP_FKS);
            return null;
        }
    });
    log.info("Warm up schemas for {}", schemasTime);

    stTotal.stop();
    log.info("Installing NDT done for {}", stTotal);
    view.setProgress(PROGRESS_OFF);
}

From source file:org.apache.brooklyn.rt.felix.EmbeddedFelixFramework.java

public static Framework newFrameworkStarted(String felixCacheDir, boolean clean, Map<?, ?> extraStartupConfig) {
    Map<Object, Object> cfg = MutableMap.copyOf(extraStartupConfig);
    if (clean)//w  w  w  .j  a  v  a  2  s.com
        cfg.put(Constants.FRAMEWORK_STORAGE_CLEAN, "onFirstInit");
    if (felixCacheDir != null)
        cfg.put(Constants.FRAMEWORK_STORAGE, felixCacheDir);
    cfg.put(Constants.FRAMEWORK_BSNVERSION, Constants.FRAMEWORK_BSNVERSION_MULTIPLE);
    FrameworkFactory factory = newFrameworkFactory();

    Stopwatch timer = Stopwatch.createStarted();
    Framework framework = factory.newFramework(cfg);
    try {
        framework.init();
        installBootBundles(framework);
        framework.start();
    } catch (Exception e) {
        // framework bundle start exceptions are not interesting to caller...
        throw Exceptions.propagate(e);
    }
    LOG.debug("System bundles are: " + SYSTEM_BUNDLES);
    LOG.debug("OSGi framework started in " + Duration.of(timer));
    return framework;
}

From source file:com.squareup.wire.sample.CodegenSample.java

private Schema loadSchema() throws IOException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    SchemaLoader loader = new SchemaLoader();
    for (String source : sources) {
        loader.addSource(new File(source));
    }/*from ww w . j  a v  a2  s  .  c om*/
    for (String proto : protos) {
        loader.addProto(proto);
    }
    Schema schema = loader.load();
    log.info("Loaded %s proto files in %s", schema.protoFiles().size(), stopwatch);
    return schema;
}

From source file:org.simmetrics.performance.BatchPerformance.java

private static void testCompareCached() {

    StringMetric metric = new StringMetricBuilder().with(new SimonWhite<String>())
            .tokenize(new WhitespaceTokenizer()).tokenize(new QGramTokenizer(2)).setTokenizerCache().build();

    Stopwatch sw = Stopwatch.createStarted();
    for (int n = 0; n < TEST_REPEATS; n++) {
        @SuppressWarnings("unused")
        final float[] results = compare(metric, name, names);

    }//  w  ww  .  jav a  2 s.  c om
    sw.stop();

    String message = "Cached performance %s ms. Repeats %s";

    System.out.println(String.format(message, sw.elapsed(TimeUnit.MILLISECONDS), TEST_REPEATS));

}

From source file:org.catrobat.catroid.common.bluetooth.ConnectionDataLogger.java

private static ArrayList<byte[]> waitForMessages(BlockingQueue<byte[]> messages, int messageByteOffset,
        int messageCountToWaitFor) {

    ArrayList<byte[]> m = new ArrayList<byte[]>();
    Stopwatch stopWatch = Stopwatch.createStarted();

    do {//  ww w. j av  a  2  s  . c o  m
        byte[] message = pollMessage(messages, TIMEOUT_SECONDS - (int) stopWatch.elapsed(TimeUnit.SECONDS));
        if (message == null) {
            return m;
        }
        m.add(BluetoothTestUtils.getSubArray(message, messageByteOffset));
    } while (m.size() < messageCountToWaitFor && stopWatch.elapsed(TimeUnit.SECONDS) < TIMEOUT_SECONDS);

    return m;
}

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

public static Transform<ResultGroups, ResultGroups> trace(final Identifier what) {
    final Stopwatch w = Stopwatch.createStarted();

    return r -> new ResultGroups(r.groups, r.errors, r.statistics,
            new QueryTrace(what, w.elapsed(TimeUnit.NANOSECONDS), ImmutableList.of(r.trace)));
}

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 {//from w w w.j  a va 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:fr.ens.transcriptome.aozan.RunDataGenerator.java

/**
 * Collect data and return a RunData object.
 * @return a RunData object with all data about the run
 * @throws AozanException if an error occurs while collecting data
 *///from w w  w  . j  a  v  a  2 s. c  om
public RunData collect() throws AozanException {

    final RunData data = new RunData();

    if (this.properties.containsKey(COLLECT_DONE)) {
        throw new AozanException("Collect has been already done.");
    }

    if (!this.properties.containsKey(QC.RTA_OUTPUT_DIR)) {
        throw new AozanException("RTA output directory is not set.");
    }

    if (!this.properties.containsKey(QC.CASAVA_DESIGN_PATH)) {
        throw new AozanException("Casava design file path is not set.");
    }

    if (!this.properties.containsKey(QC.CASAVA_OUTPUT_DIR)) {
        throw new AozanException("Casava output directory is not set.");
    }

    if (!this.properties.containsKey(QC.QC_OUTPUT_DIR)) {
        throw new AozanException("QC output directory is not set.");
    }

    if (!this.properties.containsKey(QC.TMP_DIR)) {
        throw new AozanException("Temporary directory is not set.");
    }

    // Timer
    final Stopwatch timerGlobal = Stopwatch.createStarted();

    LOGGER.info("Step collector start");

    // For all collectors
    for (final Collector collector : this.collectors) {

        final Stopwatch timerCollector = Stopwatch.createStarted();
        LOGGER.info(collector.getName().toUpperCase() + " start");

        // Configure
        collector.configure(new Properties(this.properties));

        // And collect data
        collector.collect(data);

        LOGGER.info(collector.getName().toUpperCase() + " end in "
                + toTimeHumanReadable(timerCollector.elapsed(TimeUnit.MILLISECONDS)));

    }

    for (final Collector collector : this.collectors) {
        collector.clear();
    }

    LOGGER.info("Step collector end in " + toTimeHumanReadable(timerGlobal.elapsed(TimeUnit.MILLISECONDS)));
    timerGlobal.stop();

    this.properties.setProperty(COLLECT_DONE, "true");

    return data;
}