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

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

Introduction

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

Prototype

public void start() 

Source Link

Document

Start the stopwatch.

This method starts a new timing session, clearing any previous values.

Usage

From source file:org.apache.hadoop.hbase.regionserver.IdxRegionIndexManager.java

/**
 * Fills the index. Scans the region for latest rows and sends key values
 * to the matching index builder/*from   w  w  w  . j av a2  s.c  o  m*/
 *
 * @param builders the map of builders keyed by column:qualifer pair
 * @return the keyset (a fresh set)
 * @throws IOException may be thrown by the scan
 */
private ObjectArrayList<KeyValue> fillIndex(Map<Pair<byte[], byte[]>, CompleteIndexBuilder> builders)
        throws IOException {
    ObjectArrayList<KeyValue> newKeys = this.keys == null ? new ObjectArrayList<KeyValue>() :
    // in case we already have keys in the store try to guess the new size
            new ObjectArrayList<KeyValue>(this.keys.size() + this.region.averageNumberOfMemStoreSKeys() * 2);

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

    InternalScanner scanner = region.getScanner(createScan(builders.keySet()));
    try {
        boolean moreRows;
        int id = 0;
        do {
            List<KeyValue> nextRow = new ArrayList<KeyValue>();
            moreRows = scanner.next(nextRow);
            if (nextRow.size() > 0) {
                KeyValue firstOnRow = KeyValue.createFirstOnRow(nextRow.get(0).getRow());
                newKeys.add(firstOnRow);
                // add keyvalue to the heapsize
                heapSize += firstOnRow.heapSize();
                for (KeyValue keyValue : nextRow) {
                    try {
                        CompleteIndexBuilder idx = builders
                                .get(Pair.of(keyValue.getFamily(), keyValue.getQualifier()));
                        // we must have an index since we've limited the
                        // scan to include only indexed columns
                        assert idx != null;
                        if (LOG.isTraceEnabled()) {
                            LOG.trace("About to add kv: [" + keyValue + "] with id " + id);
                        }
                        idx.addKeyValue(keyValue, id);
                    } catch (Exception e) {
                        LOG.error("Failed to add " + keyValue + " to the index", e);
                    }
                }
                id++;
            }
        } while (moreRows);
        stopWatch.stop();
        LOG.info("Filled indices for region: '" + region.getRegionNameAsString() + "' with " + id
                + " entries in " + stopWatch.toString());
        return newKeys;
    } finally {
        scanner.close();
    }
}

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;//w w w. j a v  a2s .com
    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.james.cli.ServerCmd.java

/**
 * Main method to initialize the class./*from www . jav a2s  .com*/
 *
 * @param args Command-line arguments.
 */
public static void main(String[] args) {

    try {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        CommandLine cmd = parseCommandLine(args);
        CmdType cmdType = new ServerCmd(new JmxServerProbe(cmd.getOptionValue(HOST_OPT_LONG), getPort(cmd)))
                .executeCommandLine(cmd);
        stopWatch.split();
        print(new String[] { Joiner.on(' ').join(cmdType.getCommand(), "command executed sucessfully in",
                stopWatch.getSplitTime(), "ms.") }, System.out);
        stopWatch.stop();
        System.exit(0);
    } catch (JamesCliException e) {
        failWithMessage(e.getMessage());
    } catch (ParseException e) {
        failWithMessage("Error parsing command line : " + e.getMessage());
    } catch (IOException ioe) {
        failWithMessage("Error connecting to remote JMX agent : " + ioe.getMessage());
    } catch (Exception e) {
        failWithMessage("Error while executing command:" + e.getMessage());
    }

}

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

/**
 * Run a query range test.// w w  w. j a va 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();

    int count = 1;
    while (simpleTextListener.getReceivedMsg().size() != count) {
        Thread.sleep(1000);/*from ww  w  . j  a  v a2 s.  c om*/
        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/* w  w  w .  jav  a2 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
 *///w  w w. j  av  a 2 s  .co 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 w w  . j  av  a 2s  .co m*/
        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 {//  w w w.ja v a  2 s.c  om
        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.spark.simr.Simr.java

public void startWorker() throws IOException {
    StopWatch sw = new StopWatch();
    sw.start();
    UrlCoresTuple uc = getMasterURL();//  w w w  .j ava2  s. c o  m
    sw.stop();
    if (uc == null) {
        log.warn(String.format("getMasterURL timed out in startWorker after "), sw.toString());
        return;
    }
    int uniqueId = context.getTaskAttemptID().getTaskID().getId();
    int maxCores = uc.cores;
    String masterUrl = uc.url;

    String[] exList = new String[] { masterUrl, Integer.toString(uniqueId), getLocalIP(),
            Integer.toString(maxCores) };

    redirectOutput("worker" + uniqueId);

    org.apache.spark.executor.CoarseGrainedExecutorBackend.main(exList);
}