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:jobs.ComputeNCITdistribution.java

@Override
public void doJob() throws Exception {

    Logger.info("Job started...");
    Stopwatch stopwatch = Stopwatch.createUnstarted();
    stopwatch.start();/*from www .  j a v  a 2 s.c om*/

    List<MorphiaOntologyTerm> terms = MorphiaOntologyTerm.findAll();

    int total = terms.size();
    int counter = 0;
    Directory directory = FSDirectory.open(VirtualFile.fromRelativePath("/indexes/index-2013").getRealFile());
    DirectoryReader ireader = DirectoryReader.open(directory);

    //Just chunck the words - no stop word removal - such concept will not give any result in principle
    Analyzer analyzer = new CustomStopWordsStandardAnalyzer(Version.LUCENE_47);
    IndexSearcher isearcher = new IndexSearcher(ireader);
    QueryParser parser = new QueryParser(Version.LUCENE_47, "contents", analyzer);

    for (MorphiaOntologyTerm ontologyTerm : terms) {
        counter++;

        Logger.info("i: " + counter + "/" + total);
        Stopwatch timeQuery = Stopwatch.createUnstarted();
        timeQuery.start();
        Query query = parser.parse("\"" + ontologyTerm.value + "\"");
        ScoreDoc[] hits = isearcher.search(query, null, 100000000).scoreDocs;
        timeQuery.stop();
        Logger.info("Query time: " + timeQuery.elapsed(TimeUnit.MILLISECONDS));

        Stopwatch timeUpdate = Stopwatch.createUnstarted();
        timeUpdate.start();
        ontologyTerm.frequency = hits.length;
        ontologyTerm.save();
        timeUpdate.stop();
        Logger.info("Update time: " + timeUpdate.elapsed(TimeUnit.MILLISECONDS));
        Logger.info("Query: " + ontologyTerm.value + " - " + hits.length);
    }

    stopwatch.stop();
    Utils.emailAdmin("Distribution completed",
            "Job finished in " + stopwatch.elapsed(TimeUnit.MINUTES) + " minutes.");
    Logger.info("Job finished");

}

From source file:com.jiuxian.mossrose.quartz.QuartzJobWrapper.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    try {/*from ww w.j a v  a  2s  .  c  o  m*/
        final Stopwatch watch = Stopwatch.createStarted();
        final JobHandler mJobHandler = JobHandlerFactory.getInstance()
                .getMJobHandler(ObjectContainer.getClazz(jobMeta.getId()));
        mJobHandler.handle(jobMeta, ignite, runOnMaster);
        watch.stop();
        LOGGER.info("Job {} use time: {} ms.", jobMeta.getId(), watch.elapsed(TimeUnit.MILLISECONDS));
    } catch (Exception e) {
        LOGGER.error("Error while executing job " + context.getJobDetail().getKey(), e);
    }
}

From source file:org.obm.push.store.jdbc.CollectionDaoJdbcImpl.java

@Override
public void resetCollection(Device device, CollectionId collectionId) throws DaoException {
    String statement = "DELETE FROM opush_sync_state WHERE device_id=? AND collection_id=?";
    try (Connection con = dbcp.getConnection(); PreparedStatement ps = con.prepareStatement(statement)) {
        ps.setInt(1, device.getDatabaseId());
        ps.setInt(2, collectionId.asInt());
        Stopwatch stopwatch = Stopwatch.createStarted();
        ps.executeUpdate();/*www.ja v  a 2s  . co m*/

        logger.warn("mappings & states cleared for sync of collection {} of device {}", collectionId,
                device.getDevId());
        logger.warn("Deletion time: {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
    } catch (SQLException e) {
        throw new DaoException(e);
    }
}

From source file:com.facebook.buck.distributed.MultiSourceContentsProvider.java

private ListenableFuture<Boolean> postLocalFsMaterializationHelper(boolean success,
        BuildJobStateFileHashEntry entry, Path targetAbsPath) {
    if (success) {
        fileMaterializationStatsTracker.recordLocalFileMaterialized();
        LOG.info("Materialized source file using Local Source File Cache: [%s]", targetAbsPath);
        return Futures.immediateFuture(true);
    }/*from ww w.  j a v  a  2 s .  c o m*/

    Stopwatch remoteMaterializationStopwatch = Stopwatch.createStarted();
    return Futures.transformAsync(serverContentsProvider.materializeFileContentsAsync(entry, targetAbsPath),
            (remoteSuccess) -> postRemoteMaterializationHelper(remoteSuccess, entry, targetAbsPath,
                    remoteMaterializationStopwatch.elapsed(TimeUnit.MILLISECONDS)),
            executorService);
}

From source file:com.twitter.distributedlog.io.LZ4CompressionCodec.java

@Override
public byte[] decompress(byte[] data, int offset, int length, OpStatsLogger decompressionStat) {
    Preconditions.checkNotNull(data);/*from www  . j  av  a2s  .com*/
    Preconditions.checkArgument(offset >= 0 && offset < data.length);
    Preconditions.checkArgument(length >= 0);
    Preconditions.checkNotNull(decompressionStat);

    Stopwatch watch = Stopwatch.createStarted();
    // Assume that we have a compression ratio of 1/3.
    int outLength = length * 3;
    while (true) {
        try {
            byte[] decompressed = safeDecompressor.decompress(data, offset, length, outLength);
            decompressionStat.registerSuccessfulEvent(watch.elapsed(TimeUnit.MICROSECONDS));
            return decompressed;
        } catch (LZ4Exception e) {
            outLength *= 2;
        }
    }
}

From source file:org.graylog2.system.jobs.SystemJobManager.java

public String submitWithDelay(final SystemJob job, final long delay, TimeUnit timeUnit)
        throws SystemJobConcurrencyException {
    // for immediate jobs, check allowed concurrency right now
    if (delay == 0) {
        checkAllowedConcurrency(job);/*w w  w  . j a  va  2 s  .  co m*/
    }

    final String jobClass = job.getClass().getCanonicalName();

    job.setId(new UUID().toString());
    jobs.put(job.getId(), job);

    executor.schedule(new Runnable() {
        @Override
        public void run() {
            try {
                if (delay > 0) {
                    checkAllowedConcurrency(job);
                }
                job.markStarted();

                final Stopwatch x = Stopwatch.createStarted();

                job.execute(); // ... blocks until it finishes.
                x.stop();

                final String msg = "SystemJob <" + job.getId() + "> [" + jobClass + "] finished in "
                        + x.elapsed(TimeUnit.MILLISECONDS) + "ms.";
                LOG.info(msg);
                activityWriter.write(new Activity(msg, SystemJobManager.class));
            } catch (SystemJobConcurrencyException ignored) {
            } catch (Exception e) {
                LOG.error("Unhandled error while running SystemJob <" + job.getId() + "> [" + jobClass + "]",
                        e);
            } finally {
                jobs.remove(job.getId());
            }
        }
    }, delay, timeUnit);

    LOG.info("Submitted SystemJob <{}> [{}]", job.getId(), jobClass);
    return job.getId();
}

From source file:nl.knaw.huygens.timbuctoo.tools.conversion.RelationCollectionConverter.java

public void convert() throws StorageException, IllegalArgumentException, IllegalAccessException {
    LOG.info("Start converting for Relation");
    try {/* w ww  .  j  a  v  a2s. com*/

        List<String> relationIds = Lists.newArrayList();

        //first create the jobs to prevent a mongo cursor timeout exception.
        for (StorageIterator<Relation> relations = mongoStorage.getDomainEntities(Relation.class); relations
                .hasNext();) {
            relationIds.add(relations.next().getId());

        }
        int number = 0;
        Stopwatch stopwatch = Stopwatch.createStarted();
        for (String id : relationIds) {
            versionConverter.convert(id);
            if (number % 1000 == 0) {
                commit();
                LOG.info("Time per conversion: {} ms, number of conversions {}",
                        (double) stopwatch.elapsed(TimeUnit.MILLISECONDS) / number, number);
            }
            number++;

        }
    } finally {
        commit();
        LOG.info("End converting for Relation");
    }

}

From source file:org.glowroot.container.trace.TraceService.java

public void assertNoActiveTransactions() throws Exception {
    Stopwatch stopwatch = Stopwatch.createStarted();
    // if interruptAppUnderTest() was used to terminate an active transaction, it may take a few
    // milliseconds to interrupt the thread and end the active transaction
    while (stopwatch.elapsed(SECONDS) < 2) {
        int numActiveTransactions = Integer.parseInt(httpClient.get("/backend/admin/num-active-transactions"));
        if (numActiveTransactions == 0) {
            return;
        }/*from w  w  w.  j  a va 2  s . c  o m*/
    }
    throw new AssertionError("There are still active transactions");
}

From source file:gov.nih.nci.firebird.selenium2.scalability.tests.TimedAction.java

public T time() {
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.start();//  ww  w . j  av  a  2  s  . co m
    T result;
    try {
        result = perform();
    } catch (Exception e) {
        throw new RuntimeException("Unexpected Exception in execution of " + actionName, e);
    }
    stopwatch.stop();
    long elapsedMillis = stopwatch.elapsed(TimeUnit.MILLISECONDS);
    System.out.println(actionName + " \t" + elapsedMillis);
    String timeoutMessage = "Exeuction time of " + elapsedMillis + " milliseconds exceeded timeout of "
            + timeoutSeconds + " for " + actionName;
    assertTrue(timeoutMessage, elapsedMillis <= timeoutSeconds * DateUtils.MILLIS_PER_SECOND);
    return result;
}

From source file:com.minestellar.moon.MinestellarMoon.java

@EventHandler
public void preInit(FMLPreInitializationEvent event) {
    Stopwatch stopwatch = Stopwatch.createStarted();

    new ConfigManagerMoon(new File(event.getModConfigurationDirectory(), "Minestellar/moon.cfg"));

    MoonBlocks.init();// ww w  . ja  v  a  2 s. co  m
    MoonItems.init();

    DimensionMoon.init();

    MinestellarMoon.proxy.preInit(event);

    log.info("PreInitialization Completed in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms.");
}