Example usage for org.apache.commons.lang.time StopWatch getTime

List of usage examples for org.apache.commons.lang.time StopWatch getTime

Introduction

In this page you can find the example usage for org.apache.commons.lang.time StopWatch getTime.

Prototype

public long getTime() 

Source Link

Document

Get the time on the stopwatch.

This is either the time between the start and the moment this method is called, or the amount of time between start and stop.

Usage

From source file:org.apache.hadoop.hbase.tool.Canary.java

private static void sniffRegion(final HBaseAdmin admin, final Sink sink, HRegionInfo region, HTable table)
        throws Exception {
    HTableDescriptor tableDesc = table.getTableDescriptor();
    byte[] startKey = null;
    Get get = null;//ww  w .j  a v a  2s  . c  o  m
    Scan scan = null;
    ResultScanner rs = null;
    StopWatch stopWatch = new StopWatch();
    for (HColumnDescriptor column : tableDesc.getColumnFamilies()) {
        stopWatch.reset();
        startKey = region.getStartKey();
        // Can't do a get on empty start row so do a Scan of first element if any instead.
        if (startKey.length > 0) {
            get = new Get(startKey);
            get.addFamily(column.getName());
        } else {
            scan = new Scan();
            scan.setCaching(1);
            scan.addFamily(column.getName());
            scan.setMaxResultSize(1L);
        }

        try {
            if (startKey.length > 0) {
                stopWatch.start();
                table.get(get);
                stopWatch.stop();
                sink.publishReadTiming(region, column, stopWatch.getTime());
            } else {
                stopWatch.start();
                rs = table.getScanner(scan);
                stopWatch.stop();
                sink.publishReadTiming(region, column, stopWatch.getTime());
            }
        } catch (Exception e) {
            sink.publishReadFailure(region, column, e);
        } finally {
            if (rs != null) {
                rs.close();
            }
            scan = null;
            get = null;
            startKey = null;
        }
    }
}

From source file:org.apache.ojb.broker.QueryTest.java

/**
 * Run a query range test./*from  w  w w  .  j a v  a 2s  . c om*/
 */
public void testQueryRangeMassTest() {
    String name = "testQueryRangeMassTest_" + System.currentTimeMillis();
    int objCount = 2000;

    broker.beginTransaction();
    for (int i = 0; i < objCount; i++) {
        Gourmet a = new Gourmet();
        a.setName(name);
        broker.store(a);
    }
    broker.commitTransaction();

    Criteria crit = new Criteria();
    crit.addEqualTo("name", name);
    QueryByCriteria q = QueryFactory.newQuery(Gourmet.class, crit);
    q.setStartAtIndex(100);
    q.setEndAtIndex(109);

    StopWatch watch = new StopWatch();
    watch.start();
    Collection c = broker.getCollectionByQuery(q);
    watch.stop();
    System.out.println("# Query 10 of " + objCount + " objects take " + watch.getTime() + " ms");
    assertNotNull(c);
    List result = new ArrayList(c);
    assertEquals(10, result.size());

    crit = new Criteria();
    crit.addEqualTo("name", name);
    q = QueryFactory.newQuery(Gourmet.class, crit);
    watch.reset();
    watch.start();
    c = broker.getCollectionByQuery(q);
    watch.stop();
    System.out.println("# Query all " + objCount + " objects take " + watch.getTime() + " ms");
    assertNotNull(c);
    result = new ArrayList(c);
    assertEquals(objCount, result.size());

    broker.beginTransaction();
    for (int i = 0; i < result.size(); i++) {
        broker.delete(result.get(i));
    }
    broker.commitTransaction();

    c = broker.getCollectionByQuery(q);
    assertNotNull(c);
    result = new ArrayList(c);
    assertEquals(0, result.size());
}

From source file:org.apache.rocketmq.jms.integration.listener.SimpleTextListenerTest.java

@Test
public void testListener() throws Exception {
    jmsTemplate.convertAndSend(DESTINATION, "first");
    StopWatch watch = new StopWatch();
    watch.start();/*from  w w w  .j a  va2s .  co  m*/

    int count = 1;
    while (simpleTextListener.getReceivedMsg().size() != count) {
        Thread.sleep(1000);
        log.info("Waiting for receiving {} messages sent to {} topic,now has received {}", count, DESTINATION,
                simpleTextListener.getReceivedMsg().size());
        if (watch.getTime() > 1000 * 10) {
            assertFalse(true);
        }
    }
    assertTrue(true);
}

From source file:org.apache.sling.hc.core.impl.executor.HealthCheckExecutorImpl.java

/**
 * Execute a set of health checks//from w ww  . jav  a  2  s  .c o  m
 */
private List<HealthCheckExecutionResult> execute(final ServiceReference[] healthCheckReferences,
        HealthCheckExecutionOptions options) {
    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    final List<HealthCheckExecutionResult> results = new ArrayList<HealthCheckExecutionResult>();
    final List<HealthCheckMetadata> healthCheckDescriptors = getHealthCheckMetadata(healthCheckReferences);

    createResultsForDescriptors(healthCheckDescriptors, results, options);

    stopWatch.stop();
    if (logger.isDebugEnabled()) {
        logger.debug("Time consumed for all checks: {}", msHumanReadable(stopWatch.getTime()));
    }
    // sort result
    Collections.sort(results, new Comparator<HealthCheckExecutionResult>() {

        @Override
        public int compare(final HealthCheckExecutionResult arg0, final HealthCheckExecutionResult arg1) {
            return ((ExecutionResult) arg0).compareTo((ExecutionResult) arg1);
        }

    });
    return results;
}

From source file:org.apache.sling.hc.core.impl.executor.HealthCheckExecutorImpl.java

/**
 * Wait for the futures until the timeout is reached
 *//*from   w  w  w.jav a  2  s.  c o m*/
private void waitForFuturesRespectingTimeout(final List<HealthCheckFuture> futuresForResultOfThisCall,
        HealthCheckExecutionOptions options) {
    final StopWatch callExcutionTimeStopWatch = new StopWatch();
    callExcutionTimeStopWatch.start();
    boolean allFuturesDone;

    long effectiveTimeout = this.timeoutInMs;
    if (options != null && options.getOverrideGlobalTimeout() > 0) {
        effectiveTimeout = options.getOverrideGlobalTimeout();
    }

    if (futuresForResultOfThisCall.isEmpty()) {
        return; // nothing to wait for (usually because of cached results)
    }

    do {
        try {
            synchronized (stillRunningFutures) {
                stillRunningFutures.wait(50); // wait for notifications of callbacks of HealthCheckFutures
            }
        } catch (final InterruptedException ie) {
            logger.warn("Unexpected InterruptedException while waiting for healthCheckContributors", ie);
        }

        allFuturesDone = true;
        for (final HealthCheckFuture healthCheckFuture : futuresForResultOfThisCall) {
            allFuturesDone &= healthCheckFuture.isDone();
        }
    } while (!allFuturesDone && callExcutionTimeStopWatch.getTime() < effectiveTimeout);
}

From source file:org.apache.sling.hc.core.impl.executor.HealthCheckFuture.java

HealthCheckFuture(final HealthCheckMetadata metadata, final BundleContext bundleContext,
        final Callback callback) {
    super(new Callable<ExecutionResult>() {
        @Override/*from w  ww.  j a  v a 2 s  .c  om*/
        public ExecutionResult call() throws Exception {
            Thread.currentThread().setName("HealthCheck " + metadata.getTitle());
            LOG.debug("Starting check {}", metadata);

            final StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            Result resultFromHealthCheck = null;
            ExecutionResult executionResult = null;

            final HealthCheck healthCheck = (HealthCheck) bundleContext
                    .getService(metadata.getServiceReference());

            try {
                if (healthCheck != null) {
                    resultFromHealthCheck = healthCheck.execute();
                } else {
                    throw new IllegalStateException("Service for " + metadata + " is gone");
                }

            } catch (final Exception e) {
                resultFromHealthCheck = new Result(Result.Status.CRITICAL,
                        "Exception during execution of '" + metadata.getName() + "': " + e, e);
            } finally {
                // unget service ref
                bundleContext.ungetService(metadata.getServiceReference());

                // update result with information about this run
                stopWatch.stop();
                long elapsedTime = stopWatch.getTime();
                if (resultFromHealthCheck != null) {
                    // wrap the result in an execution result
                    executionResult = new ExecutionResult(metadata, resultFromHealthCheck, elapsedTime);
                }
                LOG.debug("Time consumed for {}: {}", metadata, msHumanReadable(elapsedTime));
            }

            callback.finished(executionResult);
            Thread.currentThread().setName("HealthCheck idle");
            return executionResult;
        }
    });
    this.createdTime = new Date();
    this.metadata = metadata;

}

From source file:org.apache.solr.handler.component.RatiosComponent.java

@Override
public void process(ResponseBuilder rb) throws IOException {
    try {//www  . j  av  a  2s.  c  o m
        HashMap<String, Long> timers = new HashMap<String, Long>();

        if (rb.doRatios) {
            SolrParams params = rb.req.getParams();

            // in ratios the facet field is always the dimension field
            String dimension = params.get(RatiosParams.RATIOS_DIMENSION);
            String measure = params.get(RatiosParams.RATIOS_MEASURE);
            Double min = params.getDouble(RatiosParams.RATIOS_MIN, 0);
            Double max = params.getDouble(RatiosParams.RATIOS_MAX, 1);
            boolean debug = params.getBool(RatiosParams.RATIOS_DEBUG, false);
            boolean rows = params.getBool(RatiosParams.RATIOS_ROWS, false);

            HashMap<String, String[]> fieldFacets = new HashMap<String, String[]>();
            fieldFacets.put(measure, new String[] { dimension });

            SolrIndexSearcher searcher = rb.req.getSearcher();

            String defType = params.get(QueryParsing.DEFTYPE, QParserPlugin.DEFAULT_QTYPE);
            QParser q1 = QParser.getParser(
                    params.get("q") + " AND (" + params.get(RatiosParams.RATIOS_Q1) + ")", defType, rb.req);
            QParser q2 = QParser.getParser(
                    params.get("q") + " AND (" + params.get(RatiosParams.RATIOS_Q2) + ")", defType, rb.req);

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

            DocSet set1 = searcher.getDocSet(q1.getQuery());
            stopwatch.stop();
            timers.put("q1.ms", stopwatch.getTime());
            stopwatch.reset();

            stopwatch.start();
            DocSet set2 = searcher.getDocSet(q2.getQuery());
            stopwatch.stop();
            timers.put("q2.ms", stopwatch.getTime());
            stopwatch.reset();

            // ====== stats for 1st
            stopwatch.start();
            ModifiableSolrParams xp = new ModifiableSolrParams();
            xp.add(StatsParams.STATS_FIELD, measure);
            xp.add(StatsParams.STATS_FACET, dimension);
            xp.add(ShardParams.IS_SHARD, String.valueOf(params.getBool(ShardParams.IS_SHARD, false)));
            SimpleStats stats1 = new SimpleStats(rb.req, set1, xp);

            // TODO implement according to SOLR standard
            NamedList<?> map1 = stats1.getFieldCacheStats(measure, new String[] { dimension });
            if (map1 == null || map1.size() <= 0) {
                // empty do nothing
                return;
            }
            Map<String, Double> matrix1 = new HashMap<String, Double>(); // TODO map1.get(dimension);
            stopwatch.stop();
            timers.put("q1.stats.ms", stopwatch.getTime());
            stopwatch.reset();

            // ====== stats for 2nd
            stopwatch.start();
            SimpleStats stats2 = new SimpleStats(rb.req, set2, xp);
            NamedList<?> map2 = stats2.getFieldCacheStats(measure, new String[] { dimension });
            if (map2 == null || map2.size() <= 0) {
                // empty do nothing
                return;
            }
            Map<String, Double> matrix2 = new HashMap<String, Double>(); // TODO map2.get(dimension);
            stopwatch.stop();
            timers.put("q2.stats.ms", stopwatch.getTime());
            stopwatch.reset();

            // ====== ratios
            stopwatch.start();
            OpenBitSet ratios = new OpenBitSet();// TODO filter(matrix1, matrix2, min, max);
            stopwatch.stop();
            timers.put("ratio.ms", stopwatch.getTime());
            stopwatch.reset();

            // ====== done do payload extraction
            NamedList<Object> payload = new NamedList<Object>();
            if (debug) {
                // timer information
                NamedList<Object> performance = new NamedList<Object>();
                for (String key : timers.keySet()) {
                    performance.add(key, timers.get(key));
                }
                payload.add("debug", performance);
            }

            payload.add("count", ratios.cardinality());
            payload.add("union", set1.unionSize(set2));
            payload.add("intersection", set1.intersectionSize(set2));

            NamedList<Object> query1 = new NamedList<Object>();
            query1.add("rows", set1.size());
            query1.add("dimensions", matrix1.size());
            if (rows) {
                query1.add("results", toNamedList(matrix1));
            }

            NamedList<Object> query2 = new NamedList<Object>();
            query2.add("rows", set2.size());
            query2.add("dimensions", matrix2.size());
            if (rows) {
                query2.add("results", toNamedList(matrix2));
            }

            NamedList<Object> breakdown = new NamedList<Object>();
            breakdown.add("query1", query1);
            breakdown.add("query2", query2);

            payload.add("breakdown", breakdown);

            // TODO - output ratio bitset to hex for UX to do client side join
            // byte[] bytes = HexUtil.convertToGzipCompressedByte(ratios.getBits());
            // String x = javax.xml.bind.DatatypeConverter.printBase64Binary(bytes);
            // payload.add("base64", x);

            rb.rsp.add(RatiosParams.RATIOS, payload);
        }
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.whirr.service.hadoop.integration.benchmark.HadoopServiceTeraSortBenchmark.java

private void runTeraGen() throws IOException {
    int numTaskTrackers = controller.getCluster().getInstances().size() - 1;
    long bytesPerNode = Long.parseLong(System.getProperty("terasortBytesPerNode", "1000000000"));
    long rows = numTaskTrackers * (bytesPerNode / 100);
    StopWatch stopWatch = new StopWatch();
    TeraGen teraGen = new TeraGen();
    teraGen.setConf(controller.getJobConf());
    LOG.info("Starting TeraGen with {} tasktrackers, {} bytes per node, {} rows",
            new Object[] { numTaskTrackers, bytesPerNode, rows });
    stopWatch.start();// w ww.j ava2  s .c  o m
    teraGen.run(new String[] { "" + rows, "input" });
    stopWatch.stop();
    LOG.info("TeraGen took {} ms", stopWatch.getTime());
}

From source file:org.apache.whirr.service.hadoop.integration.benchmark.HadoopServiceTeraSortBenchmark.java

private void runTeraSort() throws Exception {
    StopWatch stopWatch = new StopWatch();
    TeraSort teraSort = new TeraSort();
    teraSort.setConf(controller.getJobConf());
    LOG.info("Starting TeraSort");
    stopWatch.start();/*from ww  w . ja  va 2s  . co  m*/
    teraSort.run(new String[] { "input", "output" });
    stopWatch.stop();
    LOG.info("TeraSort took {} ms", stopWatch.getTime());
}

From source file:org.apache.whirr.service.hadoop.integration.benchmark.HadoopServiceTeraSortBenchmark.java

private void runTeraValidate() throws Exception {
    StopWatch stopWatch = new StopWatch();
    TeraValidate teraValidate = new TeraValidate();
    teraValidate.setConf(controller.getJobConf());
    LOG.info("Starting TeraValidate");
    stopWatch.start();//w  w  w .j ava2  s. co  m
    teraValidate.run(new String[] { "output", "report" });
    stopWatch.stop();
    LOG.info("TeraValidate took {} ms", stopWatch.getTime());
}