Example usage for com.google.common.base Stopwatch Stopwatch

List of usage examples for com.google.common.base Stopwatch Stopwatch

Introduction

In this page you can find the example usage for com.google.common.base Stopwatch Stopwatch.

Prototype

Stopwatch() 

Source Link

Usage

From source file:org.apache.drill.exec.server.Drillbit.java

@Override
public synchronized void close() {
    // avoid complaints about double closing
    if (isClosed) {
        return;/*from w  w  w  .  j  ava  2  s  .  c o  m*/
    }
    final Stopwatch w = new Stopwatch().start();
    logger.debug("Shutdown begun.");

    // wait for anything that is running to complete
    manager.waitToExit();

    if (coord != null && registrationHandle != null) {
        coord.unregister(registrationHandle);
    }

    try {
        Thread.sleep(context.getConfig().getInt(ExecConstants.ZK_REFRESH) * 2);
    } catch (final InterruptedException e) {
        logger.warn("Interrupted while sleeping during coordination deregistration.");

        // Preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the
        // interruption and respond to it if it wants to.
        Thread.currentThread().interrupt();
    }

    if (embeddedJetty != null) {
        try {
            embeddedJetty.stop();
        } catch (final Exception e) {
            logger.warn("Failure while shutting down embedded jetty server.");
        }
    }

    Closeables.closeQuietly(engine);
    AutoCloseables.close(storeProvider, logger);
    Closeables.closeQuietly(coord);
    AutoCloseables.close(manager, logger);
    Closeables.closeQuietly(context);

    logger.info("Shutdown completed ({} ms).", w.elapsed(TimeUnit.MILLISECONDS));
    isClosed = true;
}

From source file:cosmos.mapred.MediawikiQueries.java

public long docIdFetch(Store id, Map<Column, Long> counts, long totalResults) throws Exception {
    Stopwatch sw = new Stopwatch();

    // This is dumb, I didn't pad the docids...
    String prev = "!";
    long resultCount = 0l;
    sw.start();//from   ww  w  . j a v  a2  s  . c  om

    final CloseableIterable<MultimapRecord> results = this.sorts.fetch(id,
            Index.define(Defaults.DOCID_FIELD_NAME));

    for (MultimapRecord r : results) {
        sw.stop();

        resultCount++;

        String current = r.docId();
        if (prev.compareTo(current) > 0) {
            System.out.println("WOAH, got " + current + " docid which was greater than the previous " + prev);
            results.close();
            System.exit(1);
        }

        prev = current;

        sw.start();
    }

    sw.stop();

    System.out.println(
            Thread.currentThread().getName() + ": docIdFetch - Took " + sw.toString() + " to fetch results");
    logTiming(totalResults, sw.elapsed(TimeUnit.MILLISECONDS), "docIdFetch");

    results.close();

    return resultCount;
}

From source file:processing.MalletCalculator.java

public static List<Map<Integer, Double>> startLdaCreation(BookmarkReader reader, int sampleSize,
        boolean sorting, int numTopics, boolean userBased, boolean resBased, boolean topicCreation,
        boolean smoothing) {
    timeString = "";
    int size = reader.getUserLines().size();
    int trainSize = size - sampleSize;

    Stopwatch timer = new Stopwatch();
    timer.start();/*from  www.ja  va2 s.  c o  m*/
    MalletCalculator userCalc = null;
    List<Map<Integer, Integer>> userMaps = null;
    //List<Double> userDenoms = null;
    if (userBased) {
        userMaps = Utilities.getUserMaps(reader.getUserLines().subList(0, trainSize));
        userCalc = new MalletCalculator(userMaps, numTopics);
        userCalc.predictValuesProbs();
        //userDenoms = getDenoms(userPredictionValues);
        System.out.println("User-Training finished");
    }
    MalletCalculator resCalc = null;
    List<Map<Integer, Integer>> resMaps = null;
    //List<Double> resDenoms = null;
    if (resBased) {
        resMaps = Utilities.getResMaps(reader.getUserLines().subList(0, trainSize));
        resCalc = new MalletCalculator(resMaps, numTopics);
        resCalc.predictValuesProbs();
        //resDenoms = getDenoms(resPredictionValues);
        System.out.println("Res-Training finished");
    }
    List<Map<Integer, Double>> results = new ArrayList<Map<Integer, Double>>();
    if (trainSize == size) {
        trainSize = 0;
    }
    timer.stop();
    long trainingTime = timer.elapsed(TimeUnit.MILLISECONDS);

    timer = new Stopwatch();
    timer.start();
    for (int i = trainSize; i < size; i++) { // the test set
        UserData data = reader.getUserLines().get(i);
        int userID = data.getUserID();
        int resID = data.getWikiID();
        //Map<Integer, Integer> userMap = null;
        //if (userBased && userMaps != null && userID < userMaps.size()) {
        //   userMap = userMaps.get(userID);
        //}
        //Map<Integer, Integer> resMap = null;
        //if (resBased && resMaps != null && resID < resMaps.size()) {
        //   resMap = resMaps.get(resID);
        //}
        double userTagCount = 0.0;//Utilities.getMapCount(userMap);
        double resTagCount = 0.0;//Utilities.getMapCount(resMap);
        /*
        double userDenomVal = 0.0;
        if (userDenoms != null && userID < userDenoms.size()) {
           userDenomVal = userDenoms.get(userID);
        }
        double resDenomVal = 0.0;
        if (resDenoms != null && resID < resDenoms.size()) {
           resDenomVal = resDenoms.get(resID);
        }
        */
        Map<Integer, Double> userPredMap = null;
        if (userCalc != null) {
            userPredMap = userCalc.getValueProbsForID(userID, topicCreation);
        }
        Map<Integer, Double> resPredMap = null;
        if (resCalc != null) {
            resPredMap = resCalc.getValueProbsForID(resID, topicCreation);
        }
        Map<Integer, Double> map = getRankedTagList(reader, userPredMap, userTagCount, resPredMap, resTagCount,
                sorting, smoothing, topicCreation);
        results.add(map);
    }
    timer.stop();
    long testTime = timer.elapsed(TimeUnit.MILLISECONDS);
    timeString += ("Full training time: " + trainingTime + "\n");
    timeString += ("Full test time: " + testTime + "\n");
    timeString += ("Average test time: " + testTime / (double) sampleSize) + "\n";
    timeString += ("Total time: " + (trainingTime + testTime) + "\n");
    return results;
}

From source file:cosmos.impl.CosmosImpl.java

@Override
public void finalize(Store id)
        throws TableNotFoundException, MutationsRejectedException, UnexpectedStateException {
    checkNotNull(id);//from   w w w .j av  a 2 s .c  o m

    Stopwatch sw = new Stopwatch().start();

    try {
        State s = PersistedStores.getState(id);

        if (!State.LOADING.equals(s)) {
            throw unexpectedState(id, State.LOADING, s);
        }

        final State desiredState = State.LOADED;

        log.debug("Changing state for {} from {} to {}", new Object[] { id, s, desiredState });

        PersistedStores.setState(id, desiredState);
    } finally {
        sw.stop();
        id.tracer().addTiming("Cosmos:finalize", sw.elapsed(TimeUnit.MILLISECONDS));
    }
}

From source file:uk.ac.open.kmi.iserve.sal.manager.impl.ServiceManagerIndexRdf.java

/**
 * This method will be called when the server is initialised.
 * If necessary it should take care of updating any indexes on boot time.
 *///from  ww  w .  j a v a  2 s.  c om
private void initialise() {
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.start();
    populateCache();
    stopwatch.stop();
    log.info("Cache populated. Time taken {}", stopwatch);
}

From source file:ubic.gemma.persistence.service.expression.experiment.GeeqServiceImpl.java

/**
 * Does all the preparations and calls the appropriate scoring methods.
 *
 * @param eeId the id of experiment to be scored.
 * @param mode the mode of scoring. All will redo all scores, batchEffect and batchConfound will only recalculate
 *             scores relevant to batch effect and batch confound, respectively.
 *             Scoring batch effect and confound is fairly fast, especially compared to the 'all' mode, which goes
 *             through almost all information associated with the experiment, and can therefore be very slow,
 *             depending on the experiment.
 *///  www . j  a v  a 2  s  . c om
private void doScoring(Long eeId, String mode) {
    ExpressionExperiment ee = expressionExperimentService.load(eeId);

    if (ee == null) {
        return;
    }

    this.ensureEeHasGeeq(ee);
    Geeq gq = ee.getGeeq();

    Stopwatch stopwatch = new Stopwatch();
    stopwatch.start();

    try {
        // Update score values
        switch (mode) {
        case GeeqService.OPT_MODE_ALL:
            Log.info(this.getClass(),
                    GeeqServiceImpl.LOG_PREFIX + " Starting full geeq scoring for ee id " + eeId);
            gq = this.scoreAll(ee);
            break;
        case GeeqService.OPT_MODE_BATCH:
            Log.info(this.getClass(), GeeqServiceImpl.LOG_PREFIX
                    + " Starting batch info, confound and batch effect geeq re-scoring for ee id " + eeId);
            gq = this.scoreOnlyBatchArtifacts(ee);
            break;
        case GeeqService.OPT_MODE_REPS:
            Log.info(this.getClass(),
                    GeeqServiceImpl.LOG_PREFIX + " Starting replicates geeq re-scoring for ee id " + eeId);
            gq = this.scoreOnlyReplicates(ee);
            break;
        case GeeqService.OPT_MODE_PUB:
            Log.info(this.getClass(),
                    GeeqServiceImpl.LOG_PREFIX + " Starting publication geeq re-scoring for ee id " + eeId);
            gq = this.scoreOnlyPublication(ee);
            break;
        default:
            Log.warn(this.getClass(), GeeqServiceImpl.LOG_PREFIX + " Did not recognize the given mode " + mode
                    + " for ee id " + eeId);
        }
        Log.info(this.getClass(), GeeqServiceImpl.LOG_PREFIX + " Finished geeq re-scoring for ee id " + eeId
                + ", saving results...");
    } catch (Exception e) {
        Log.info(this.getClass(), GeeqServiceImpl.LOG_PREFIX
                + " Major problem encountered, scoring did not finish for ee id " + eeId + ".");
        e.printStackTrace();
        gq.addOtherIssues(e.getMessage());
    }

    // Recalculate final scores
    gq = this.updateQualityScore(gq);
    gq = this.updateSuitabilityScore(gq);

    // Add note if experiment curation not finished
    if (ee.getCurationDetails().getNeedsAttention()) {
        gq.addOtherIssues("Experiment was not fully curated when the score was calculated.");
    }

    stopwatch.stop();
    gq.setLastRun(this.createGeeqEvent(ee, "Re-ran geeq scoring (mode: " + mode + ")", "Took "
            + stopwatch.elapsedMillis() + "ms.\nUnexpected problems encountered: \n" + gq.getOtherIssues()));

    this.update(gq);
    Log.info(this.getClass(), GeeqServiceImpl.LOG_PREFIX + " took "
            + Math.round(stopwatch.elapsedTime(TimeUnit.SECONDS) / 60.0) + " minutes to process ee id " + eeId);

}

From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java

protected int executeMethod(ProxyRepository repository, ResourceStoreRequest request, HttpMethod method,
        URL remoteUrl) throws RemoteStorageException {
    final Stopwatch stopwatch = timingLog.isDebugEnabled() ? new Stopwatch().start() : null;
    try {/*from   w w  w . ja v  a2  s  .c om*/
        return doExecuteMethod(repository, request, method, remoteUrl);
    } finally {
        if (stopwatch != null) {
            stopwatch.stop();
            timingLog.debug("[{}] {} {} took {}",
                    new Object[] { repository.getId(), method.getName(), remoteUrl, stopwatch });
        }
    }
}

From source file:de.hybris.platform.acceleratorcms.component.slot.impl.DefaultCMSPageSlotComponentService.java

@Override
public void renderComponent(final PageContext pageContext, final AbstractCMSComponentModel component)
        throws ServletException, IOException {
    validateParameterNotNull(pageContext, "Parameter pageContext must not be null");
    validateParameterNotNull(component, "Parameter component must not be null");

    if (LOG.isDebugEnabled()) {
        final Stopwatch stopwatch = new Stopwatch();

        stopwatch.start();/*from   w ww  .j a  v a  2  s. c  o m*/
        getCmsComponentRenderer().renderComponent(pageContext, component);
        stopwatch.stop();

        if (stopwatch.elapsedMillis() > 1) {
            LOG.debug("Rendered component [" + component.getUid() + "] of type [" + component.getItemtype()
                    + "].. (" + stopwatch.toString() + ")");
        }
    } else {
        getCmsComponentRenderer().renderComponent(pageContext, component);
    }
}

From source file:cosmos.mapred.MediawikiQueries.java

public long columnFetch(Store id, Column colToFetch, Map<Column, Long> counts, long totalResults)
        throws Exception {
    Stopwatch sw = new Stopwatch();
    String prev = null;//from   www  .  ja  v  a  2  s. c  o m
    String lastDocId = null;
    long resultCount = 0l;

    sw.start();
    final CloseableIterable<MultimapRecord> results = this.sorts.fetch(id, Index.define(colToFetch));
    Iterator<MultimapRecord> resultsIter = results.iterator();

    for (; resultsIter.hasNext();) {
        MultimapRecord r = resultsIter.next();

        sw.stop();
        resultCount++;

        Collection<RecordValue<?>> values = r.get(colToFetch);

        TreeSet<RecordValue<?>> sortedValues = Sets.newTreeSet(values);

        if (null == prev) {
            prev = sortedValues.first().value().toString();
        } else {
            boolean plausible = false;
            Iterator<RecordValue<?>> iter = sortedValues.iterator();
            for (; !plausible && iter.hasNext();) {
                String val = iter.next().value().toString();
                if (prev.compareTo(val) <= 0) {
                    plausible = true;
                }
            }

            if (!plausible) {
                System.out.println(Thread.currentThread().getName() + ": " + colToFetch + " - " + lastDocId
                        + " shouldn't have come before " + r.docId());
                System.out.println(prev + " compared to " + sortedValues);
                results.close();
                System.exit(1);
            }
        }

        lastDocId = r.docId();

        sw.start();
    }

    sw.stop();

    System.out.println(Thread.currentThread().getName() + ": " + colToFetch + " - Took " + sw.toString()
            + " to fetch results");
    logTiming(totalResults, sw.elapsed(TimeUnit.MILLISECONDS), "fetch:" + colToFetch);

    results.close();

    long expected = counts.containsKey(colToFetch) ? counts.get(colToFetch) : -1;

    if (resultCount != expected) {
        System.out.println(Thread.currentThread().getName() + " " + colToFetch + ": Expected to get " + expected
                + " records but got " + resultCount);
        System.exit(1);
    }

    return resultCount;
}

From source file:cosmos.impl.CosmosImpl.java

@Override
public void index(Store id, Set<Index> columnsToIndex) throws Exception {
    checkNotNull(id);/*from   w  w  w  .j a  v a2  s . c o m*/
    checkNotNull(columnsToIndex);

    Stopwatch sw = new Stopwatch().start();

    try {
        State s = PersistedStores.getState(id);

        if (!State.LOADING.equals(s) && !State.LOADED.equals(s)) {
            // stopwatch stopped by finally
            throw unexpectedState(id, new State[] { State.LOADING, State.LOADED }, s);
        }

        InterProcessMutex lock = getMutex(id);

        boolean locked = false;
        int count = 1;

        // Only perform locking when the client requests it
        if (id.lockOnUpdates()) {
            while (!locked && count < 4) {
                if (locked = lock.acquire(10, TimeUnit.SECONDS)) {
                    try {
                        performUpdate(id, columnsToIndex);

                    } finally {
                        lock.release();
                    }

                    return;
                } else {
                    count++;
                    log.warn("index() on {} could not acquire lock after {} seconds. Attempting acquire #{}",
                            new Object[] { id.uuid(), LOCK_SECS, count });
                }

                throw new IllegalStateException(
                        "Could not acquire lock during index() after " + count + " attempts");
            }
        } else {
            performUpdate(id, columnsToIndex);
        }
    } finally {
        sw.stop();
        id.tracer().addTiming("Cosmos:index", sw.elapsed(TimeUnit.MILLISECONDS));
    }
}