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:com.Grande.GSM.BACCWS_WAR.WS.REST.EOS.FirmwareDefinitionsEndpoint.java

@GET
public String fetchFirmwareDefinitionsByMakeModel(@QueryParam("make") final String strMake,
        @QueryParam("model") final String strModel) {

    // <editor-fold defaultstate="collapsed" desc="****** Method vars ******">
    final Stopwatch timer = new Stopwatch();
    final QueryResponse qRes = new QueryResponse();
    String strResponse = null;//from w  w w.j  ava2s. c  o m
    FirmwareDefinition fdThis = null;
    // start the execution timer
    timer.start();
    // </editor-fold>

    try {

        qRes.vSetNode(java.net.InetAddress.getLocalHost().getHostName());

        fdThis = this.trnBN.pGetFirmwareDefinitionByMakeAndModel(strMake, strModel)
                .orElseThrow(() -> new Exception(
                        "Make/model \"" + strMake + "/" + strModel + "\" not found in the firmware table"));
        qRes.vSetSuccessFlag(true);
        qRes.vAddResult(fdThis);

    } catch (Exception e) {

        // <editor-fold defaultstate="collapsed" desc="****** Handle failures ******">
        qRes.vSetSuccessFlag(false);
        // handle NPE differently since getMessage() is null
        if (e instanceof NullPointerException) {
            qRes.vSetMessage("NPE occured when serializing result to JSON! " + "File: "
                    + e.getStackTrace()[0].getFileName() + ", " + "Method: "
                    + e.getStackTrace()[0].getMethodName() + ", " + "Line: "
                    + e.getStackTrace()[0].getLineNumber());
        } else {
            qRes.vSetMessage(e.getMessage());
        }
        SimpleLogging.vLogException(this.strThreadId, e);
        // </editor-fold>

    } finally {

        // <editor-fold defaultstate="collapsed" desc="****** Stop timer, convert response to JSON ******">
        timer.stop();
        qRes.vSetRoundTrip(String.valueOf(timer.elapsedTime(TimeUnit.SECONDS)) + "."
                + String.valueOf(timer.elapsedTime(TimeUnit.MILLISECONDS)));
        strResponse = this.trnBN.strQueryResponseToJSON(qRes);
        SimpleLogging.vLogEvent(this.strThreadId + "|" + qRes.strGetRoundTripInSeconds() + "s",
                "retrieved " + qRes.intGetDataCount() + " records");
        // </editor-fold>

    }
    return strResponse;
}

From source file:org.apache.drill.exec.physical.impl.sort.SortTemplate.java

@Override
public void sort(SelectionVector4 vector4, VectorContainer container) {
    Stopwatch watch = new Stopwatch();
    watch.start();// w ww.j a v a2  s .c  o m
    QuickSort qs = new QuickSort();
    qs.sort(this, 0, vector4.getTotalCount());
    logger.debug("Took {} us to sort {} records", watch.elapsed(TimeUnit.MICROSECONDS),
            vector4.getTotalCount());
}

From source file:demos.SynchronousRead.java

public void run() {
    logger.info("Preparing to read data points");

    Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
    Session session = cluster.connect("demo");
    PreparedStatement query = session.prepare(
            "SELECT metric_id, time, value FROM metric_data WHERE metric_id = ? AND time >= ? AND time <= ?");
    DateTime end = DateTime.now();//from w ww . j av  a  2s.c o m
    DateTime start = end.minusYears(1);
    List<DataPoint> dataPoints = new ArrayList<>();

    Stopwatch stopwatch = new Stopwatch().start();
    for (int i = 0; i < NUM_METRICS; ++i) {
        ResultSet resultSet = session.execute(query.bind("metric-" + i, start.toDate(), end.toDate()));
        resultSet.forEach(
                row -> dataPoints.add(new DataPoint(row.getString(0), row.getDate(1), row.getDouble(2))));
    }
    stopwatch.stop();

    logger.info("Retrieved {} data points in {} ms", dataPoints.size(),
            stopwatch.elapsed(TimeUnit.MILLISECONDS));
}

From source file:org.deephacks.westty.internal.core.WesttyCore.java

public void startup() {
    log.info("Westty startup.");
    try {/*from w  w  w.j av  a 2  s . c o  m*/
        Stopwatch time = new Stopwatch().start();
        if (!Strings.isNullOrEmpty(APPLICATION_CONF)) {
            File conf = new File(APPLICATION_CONF);
            if (conf.exists()) {
                System.setProperty(APPLICATION_CONF_PROP, conf.getAbsolutePath());
            }
        }
        weld = new Weld();
        container = weld.initialize();
        log.info("Weld started.");

        engine = container.instance().select(WesttyEngine.class).get();
        engine.start();
        ShutdownHook.install(new Thread("WesttyShutdownHook") {
            @Override
            public void run() {
                shutdown();
            }
        });
        log.info("Westty started in {} ms.", time.elapsedMillis());
    } catch (Exception e) {
        log.error("Exception during startup", e);
        shutdown();
        throw new RuntimeException(e);
    }
}

From source file:org.apache.drill.exec.physical.impl.xsort.SingleBatchSorterTemplate.java

@Override
public void sort(SelectionVector2 vector2) {
    QuickSort qs = new QuickSort();
    Stopwatch watch = new Stopwatch();
    watch.start();/*from  ww  w.  j a  v a  2  s .c o  m*/
    if (vector2.getCount() > 0) {
        qs.sort(this, 0, vector2.getCount());
    }
    logger.debug("Took {} us to sort {} records", watch.elapsed(TimeUnit.MICROSECONDS), vector2.getCount());
}

From source file:de.blizzy.documentr.access.BCryptPasswordEncoder.java

@Override
public String encodePassword(String rawPass, Object salt) {
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.start();//from ww w  .jav  a2 s .c  om
    String encPass = encoder.encode(rawPass);
    stopwatch.stop();
    if (log.isTraceEnabled()) {
        log.trace("time taken to encode password: {} ms", stopwatch.elapsedMillis()); //$NON-NLS-1$
    }
    return encPass;
}

From source file:com.googlecode.concurrentlinkedhashmap.Profile.java

void scheduleStatusTask() {
    Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(new Runnable() {
        final Stopwatch stopwatch = new Stopwatch();

        @Override/*  ww w.j a v  a2s .com*/
        public void run() {
            if (!stopwatch.isRunning()) {
                System.out.println("Warmup complete");
                calls = new LongAdder();
                stopwatch.start();
                return;
            }
            long count = calls.longValue();
            long rate = count / stopwatch.elapsed(TimeUnit.SECONDS);
            System.out.printf("%s - %,d [%,d / sec]\n", stopwatch, count, rate);
        }
    }, WARM_UP_SEC, DISPLAY_DELAY_SEC, TimeUnit.SECONDS);
}

From source file:at.sti2.sparkwave.parser.StreamParserThread.java

public void run() {

    long tripleCounter = 0;

    try {//ww w.j  a  va 2s  . com

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

        while (run) {

            // Get triple from the stream
            Triple triple = getTriple();
            tripleCounter++;

            if (!triple.isPoisonTriple()) {

                long currentTimeMillis = System.currentTimeMillis();
                triple.setTimestamp(currentTimeMillis);

                //synchronized because it might happen that SparkwaveKernel thread removes a queue from queues
                synchronized (queues) {
                    // put triple in all queues
                    for (BlockingQueue<Triple> queue : queues) {
                        queue.put(triple);
                    }
                }
            } else {
                run = false;
            }
        }

        stopWatch.stop();

        StringBuffer timeBuffer = new StringBuffer();
        timeBuffer.append("Streaming took [" + stopWatch.elapsedTime(TimeUnit.MILLISECONDS) + "ms] ");
        timeBuffer.append(stopWatch.elapsedTime(TimeUnit.MINUTES));
        timeBuffer.append(" min ");
        timeBuffer.append(stopWatch.elapsedTime(TimeUnit.SECONDS));
        timeBuffer.append(" s ");
        timeBuffer.append(stopWatch.elapsedTime(TimeUnit.MILLISECONDS));
        timeBuffer.append(" ms.");

        logger.info(timeBuffer.toString());
        logger.info("Processed " + tripleCounter + " triples.");
        //         logger.info("Pattern has been matched "+ sparkwaveNetwork.getReteNetwork().getNumMatches()+ " times.");

    } catch (InterruptedException e) {
        logger.error(e.getMessage());
    }
}

From source file:org.apache.drill.exec.physical.impl.ImplCreator.java

/**
 * Create and return fragment RootExec for given FragmentRoot. RootExec has one or more RecordBatches as children
 * (which may contain child RecordBatches and so on).
 *
 * @param context/*  w w  w .j  a v a2  s  .co  m*/
 *          FragmentContext.
 * @param root
 *          FragmentRoot.
 * @return RootExec of fragment.
 * @throws ExecutionSetupException
 */
public static RootExec getExec(FragmentContext context, FragmentRoot root) throws ExecutionSetupException {
    Preconditions.checkNotNull(root);
    Preconditions.checkNotNull(context);

    if (AssertionUtil.isAssertionsEnabled()) {
        root = IteratorValidatorInjector.rewritePlanWithIteratorValidator(context, root);
    }
    final ImplCreator creator = new ImplCreator();
    Stopwatch watch = new Stopwatch();
    watch.start();

    try {
        final RootExec rootExec = creator.getRootExec(root, context);
        // skip over this for SimpleRootExec (testing)
        if (rootExec instanceof BaseRootExec) {
            ((BaseRootExec) rootExec).setOperators(creator.getOperators());
        }

        logger.debug("Took {} ms to create RecordBatch tree", watch.elapsed(TimeUnit.MILLISECONDS));
        if (rootExec == null) {
            throw new ExecutionSetupException(
                    "The provided fragment did not have a root node that correctly created a RootExec value.");
        }

        return rootExec;
    } catch (Exception e) {
        context.fail(e);
        for (final CloseableRecordBatch crb : creator.getOperators()) {
            AutoCloseables.close(crb, logger);
        }
    }

    return null;
}

From source file:co.cask.cdap.test.AbstractAdapterManager.java

@Override
public void waitForRunsToFinish(int numRuns, long timeout, TimeUnit timeoutUnit)
        throws TimeoutException, InterruptedException {
    long sleepMillis = getSleepTime(timeout, timeoutUnit);
    int numFinished = 0;

    Stopwatch stopwatch = new Stopwatch().start();
    while (stopwatch.elapsedTime(timeoutUnit) < timeout) {
        numFinished = 0;//from w  w w.  j  ava2  s  . co m
        for (RunRecord record : getRuns()) {
            if (record.getStatus() != ProgramRunStatus.RUNNING) {
                numFinished++;
            }
        }
        if (numFinished < numRuns) {
            TimeUnit.MILLISECONDS.sleep(sleepMillis);
        } else {
            break;
        }
    }

    if (numFinished < numRuns) {
        throw new TimeoutException("Time limit reached.");
    }
}