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.google.api.ads.adwords.awreporting.processors.onmemory.ReportProcessorOnMemory.java

/**
 * Generate all the mapped reports to the given account IDs.
 *
 * @param dateRangeType the date range type.
 * @param dateStart the starting date./*from   w  w  w .  jav a 2s  .c  om*/
 * @param dateEnd the ending date.
 * @param accountIdsSet the account IDs.
 * @param properties the properties file
 * @throws Exception error reaching the API.
 */
@Override
public void generateReportsForMCC(String mccAccountId, ReportDefinitionDateRangeType dateRangeType,
        String dateStart, String dateEnd, Set<Long> accountIdsSet, Properties properties,
        ReportDefinitionReportType onDemandReportType, List<String> reportFieldsToInclude) throws Exception {

    LOGGER.info("*** Retrieving account IDs ***");

    if (accountIdsSet == null || accountIdsSet.size() == 0) {
        accountIdsSet = this.retrieveAccountIds(mccAccountId);
    } else {
        LOGGER.info("Accounts loaded from file.");
    }

    AdWordsSessionBuilderSynchronizer sessionBuilder = new AdWordsSessionBuilderSynchronizer(
            authenticator.authenticate(mccAccountId, false), getIncludeZeroImpressions(properties));

    LOGGER.info("*** Generating Reports for " + accountIdsSet.size() + " accounts ***");

    Stopwatch stopwatch = Stopwatch.createStarted();

    // reports
    Set<ReportDefinitionReportType> reports = this.csvReportEntitiesMapping.getDefinedReports();

    Set<Object> propertiesKeys = properties.keySet();
    for (Object key : propertiesKeys) {

        String reportDefinitionKey = key.toString();
        ReportDefinitionReportType reportType = this.extractReportTypeFromKey(reportDefinitionKey);
        if (reportType != null && reports.contains(reportType)) {
            this.downloadAndProcess(mccAccountId, sessionBuilder, reportType, dateRangeType, dateStart, dateEnd,
                    accountIdsSet, reportDefinitionKey, properties);
        }
    }

    stopwatch.stop();
    LOGGER.info("*** Finished processing all reports in " + (stopwatch.elapsed(TimeUnit.MILLISECONDS) / 1000)
            + " seconds ***\n");
}

From source file:org.apache.jackrabbit.oak.plugins.document.secondary.SecondaryStoreObserver.java

@Override
public void contentChanged(@Nonnull NodeState root, @Nullable CommitInfo info) {
    //Diff here would also be traversing non visible areas and there
    //diffManyChildren might pose problem for e.g. data under uuid index
    if (!firstEventProcessed) {
        log.info("Starting initial sync");
    }//from  ww  w . j a va  2 s .com

    Stopwatch w = Stopwatch.createStarted();
    AbstractDocumentNodeState target = (AbstractDocumentNodeState) root;
    NodeState secondaryRoot = nodeStore.getRoot();
    NodeState base = DelegatingDocumentNodeState.wrapIfPossible(secondaryRoot, differ);
    NodeBuilder builder = secondaryRoot.builder();
    ApplyDiff diff = new PathFilteringDiff(builder, pathFilter, target);

    //Copy the root node meta properties
    PathFilteringDiff.copyMetaProperties(target, builder);

    //Apply the rest of properties
    target.compareAgainstBaseState(base, diff);
    try {
        NodeState updatedSecondaryRoot = nodeStore.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
        secondaryObserver.contentChanged(DelegatingDocumentNodeState.wrap(updatedSecondaryRoot, differ));

        TimerStats timer = info == null ? external : local;
        timer.update(w.elapsed(TimeUnit.NANOSECONDS), TimeUnit.NANOSECONDS);

        if (!firstEventProcessed) {
            log.info("Time taken for initial sync {}", w);
            firstEventProcessed = true;
        }
    } catch (CommitFailedException e) {
        //TODO
        log.warn("Commit to secondary store failed", e);
    }
}

From source file:uk.ac.ebi.atlas.solr.query.SolrQueryService.java

public Set<String> fetchGeneIds(String geneQuery, boolean exactMatch, String species) {

    Stopwatch stopwatch = Stopwatch.createStarted();

    //eg: {!lucene q.op=OR df=property_value_lower}(property_value_lower:Q9NHV9) AND (bioentity_type:"mirna" OR bioentity_type:"ensgene")
    // fl=bioentity_identifier&group=true&group.field=bioentity_identifier&group.main=true
    SolrQuery solrQuery = solrQueryBuilderFactory.createGeneBioentityIdentifierQueryBuilder()
            .forQueryString(geneQuery, true).withExactMatch(exactMatch).withSpecies(species)
            .withBioentityTypes(GENE.getSolrAliases()).build();

    Set<String> geneIds = solrServer.query(solrQuery, BIOENTITY_IDENTIFIER_FIELD, false);

    stopwatch.stop();/*from w  w w .  j a v  a 2  s  .c  o m*/
    LOGGER.debug(String.format("Fetched gene ids for %s: returned %s results in %s secs", geneQuery,
            geneIds.size(), stopwatch.elapsed(TimeUnit.MILLISECONDS) / 1000D));

    return geneIds;
}

From source file:ezbake.groups.service.CachingEzGroupsService.java

public void logStopwatch(Stopwatch timer, String message, Object... args) {
    if (logTimer) {
        message = String.format(message, args);
        logger.info("TIMER: {} ----------> {}ms", message, timer.elapsed(TimeUnit.MILLISECONDS));
    }//  w w w.  j  av  a  2  s  .c o  m
}

From source file:com.google.api.ads.adwords.awalerting.processor.AlertActionsProcessor.java

/**
 * Process the ReportData list with alert actions, all reports with each action per thread.
 *
 * @param reports the list of ReportData to run each alert action against.
 *//*from w  ww  . j a va  2s .  c  om*/
public void processReports(List<ReportData> reports) throws AlertProcessingException {
    // Create one thread for each AlertAction, and process all reports
    Stopwatch stopwatch = Stopwatch.createStarted();

    CountDownLatch latch = new CountDownLatch(actions.size());
    ExecutorService executorService = Executors.newFixedThreadPool(numThreads);

    for (AlertAction action : actions) {
        RunnableAlertActionProcessor actionProcessor = new RunnableAlertActionProcessor(action, reports);
        executeRunnableAlertActionProcessor(executorService, actionProcessor, latch);
    }

    try {
        latch.await();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new AlertProcessingException("AlertActionsProcessor encounters InterruptedException.", e);
    }

    executorService.shutdown();
    stopwatch.stop();

    LOGGER.info("*** Processed {} actions on {} reports in {} seconds.", actions.size(), reports.size(),
            stopwatch.elapsed(TimeUnit.MILLISECONDS) / 1000);
}

From source file:org.apache.drill.common.scanner.persistence.ScanResult.java

/**
 * This will load all the scanned classes for this parent as a side effect
 * @param c the parent//from  w w w.j  a  v a2s  .  c om
 * @return all the classes found
 */
public <T> Set<Class<? extends T>> getImplementations(Class<T> c) {
    ParentClassDescriptor p = getImplementations(c.getName());
    Stopwatch watch = Stopwatch.createStarted();
    Set<Class<? extends T>> result = new HashSet<>();
    try {
        if (p != null) {
            for (ChildClassDescriptor child : p.getChildren()) {
                if (!child.isAbstract()) {
                    try {
                        result.add(Class.forName(child.getName()).asSubclass(c));
                    } catch (ClassNotFoundException e) {
                        throw new DrillRuntimeException("scanned class could not be found: " + child.getName(),
                                e);
                    }
                }
            }
        }
        return result;
    } finally {
        logger.info(format("loading %d classes for %s took %dms", result.size(), c.getName(),
                watch.elapsed(MILLISECONDS)));
    }
}

From source file:com.xiaomi.linden.service.CoreLindenServiceImpl.java

@Override
public Future<Response> handleClusterCommand(final String command) {
    final Stopwatch sw = Stopwatch.createStarted();
    return clusterExecutorPool.apply(new Function0<Response>() {
        @Override/*  w  ww. j  a  v  a2s  .  c o m*/
        public Response apply() {
            Response response = null;
            String logTag = null;
            try {
                long eps = sw.elapsed(TimeUnit.MILLISECONDS);
                if (eps > 10) {
                    LOGGER.warn(
                            "Warning: clusterExecutorPool took " + eps + "ms to start handleClusterCommand.");
                    if (eps > clusterFuturePoolWaitTimeout) {
                        response = ResponseUtils.buildFailedResponse(
                                "Waiting time is too long, " + eps + "ms in cluster future pool");
                        return response;
                    }
                }
                response = lindenCluster.executeCommand(command);
                if (response.isSuccess()) {
                    logTag = "command";
                } else {
                    logTag = "failureCommand";
                }
            } catch (Exception e) {
                String errorStackInfo = Throwables.getStackTraceAsString(e);
                response = ResponseUtils.buildFailedResponse(errorStackInfo);
                logTag = "exceptionalCommand";
            } finally {
                metricsManager.time(sw.elapsed(TimeUnit.NANOSECONDS), logTag);
                if (response.isSuccess()) {
                    LOGGER.info("handleClusterCommand succeeded command: {}, cost: {} ms.", command,
                            sw.elapsed(TimeUnit.MILLISECONDS));
                } else {
                    LOGGER.error("handleClusterCommand failed command: {}, cost: {} ms.", command,
                            sw.elapsed(TimeUnit.MILLISECONDS));
                }
                return response;
            }
        }
    });
}

From source file:com.xiaomi.linden.service.CoreLindenServiceImpl.java

@Override
public Future<Response> handleClusterDeleteRequest(final String bql) {
    final Stopwatch sw = Stopwatch.createStarted();
    return clusterExecutorPool.apply(new Function0<Response>() {
        @Override// w  ww .  j  a v a  2  s . c o m
        public Response apply() {
            Response response = null;
            String logTag = null;
            try {
                long eps = sw.elapsed(TimeUnit.MILLISECONDS);
                if (eps > 10) {
                    LOGGER.warn("Warning: clusterExecutorPool took " + eps
                            + "ms to start handleClusterDeleteRequest.");
                    if (eps > clusterFuturePoolWaitTimeout) {
                        response = ResponseUtils.buildFailedResponse(
                                "Waiting time is too long, " + eps + "ms in cluster future pool");
                        return response;
                    }
                }
                LindenRequest request = bqlCompiler.compile(bql);
                if (request.isSetDeleteRequest()) {
                    response = lindenCluster.delete(request.getDeleteRequest());
                    if (response.isSuccess()) {
                        logTag = "delete";
                    } else {
                        logTag = "failureDelete";
                    }
                } else {
                    response = ResponseUtils.buildFailedResponse("invalid delete Bql");
                    logTag = "invalidDeleteBql";
                }
            } catch (Exception e) {
                String errorStackInfo = Throwables.getStackTraceAsString(e);
                response = ResponseUtils.buildFailedResponse(errorStackInfo);
                logTag = "exceptionalDeleteBql";
            } finally {
                metricsManager.time(sw.elapsed(TimeUnit.NANOSECONDS), logTag);
                if (response.isSuccess()) {
                    LOGGER.info("Cluster delete succeeded bql: {}, cost: {} ms.", bql,
                            sw.elapsed(TimeUnit.MILLISECONDS));
                } else {
                    LOGGER.error("Cluster delete failed bql: {}, cost: {} ms.", bql,
                            sw.elapsed(TimeUnit.MILLISECONDS));
                }
                return response;
            }
        }
    });
}

From source file:com.github.ibole.microservice.security.auth.jwt.jose4j.EcJose4jTokenAuthenticator.java

/**
 * Create Refresh Token./*from   w w  w.  j a va2s. c om*/
 */
@Override
public String createRefreshToken(JwtObject claimObj) throws TokenHandlingException {
    Preconditions.checkArgument(claimObj != null, "Parameter claimObj cannot be null");
    final Stopwatch stopwatch = Stopwatch.createStarted();
    String token = null;
    try {

        token = JoseUtils.createJwtWithECKey(claimObj, (EllipticCurveJsonWebKey) ecJsonWebKey);
        getCacheService().set(getRefreshTokenKey(claimObj.getLoginId()), Constants.REFRESH_TOKEN, token);
        getCacheService().set(getRefreshTokenKey(claimObj.getLoginId()), Constants.CLIENT_ID,
                claimObj.getClientId());
        getCacheService().expire(getRefreshTokenKey(claimObj.getLoginId()), claimObj.getTtlSeconds());

    } catch (JoseException ex) {
        logger.error("Error happened when generating the jwt token.", ex);
        throw new TokenHandlingException(ex);
    }
    String elapsedString = Long.toString(stopwatch.elapsed(TimeUnit.MILLISECONDS));
    logger.debug("Create refresh token elapsed time: {} ms", elapsedString);
    return token;
}

From source file:org.apache.hive.ptest.execution.HostExecutor.java

/**
 * @return failed tests//from  w w w .  j  a  v  a 2s .co  m
 */
ListenableFuture<Void> submitTests(final BlockingQueue<TestBatch> parallelWorkQueue,
        final BlockingQueue<TestBatch> isolatedWorkQueue, final Set<TestBatch> failedTestResults) {
    return mExecutor.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            Stopwatch stopwatch = Stopwatch.createStarted();
            mLogger.info("Starting SubmitTests on host {}", getHost());
            try {
                executeTests(parallelWorkQueue, isolatedWorkQueue, failedTestResults);
            } finally {
                stopwatch.stop();
                mLogger.info(
                        "Finishing submitTests on host: {}. ElapsedTime(ms)={},"
                                + " NumParallelBatchesProcessed={}, NumIsolatedBatchesProcessed={}",
                        new Object[] { getHost().toString(), stopwatch.elapsed(TimeUnit.MILLISECONDS),
                                numParallelBatchesProcessed, numIsolatedBatchesProcessed });
            }
            return null;
        }

    });
}