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

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

Introduction

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

Prototype

public Stopwatch start() 

Source Link

Document

Starts the stopwatch.

Usage

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();
        getCmsComponentRenderer().renderComponent(pageContext, component);
        stopwatch.stop();// w  w  w . j  a  v  a 2s. c  om

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

From source file:edu.umkc.sce.App.java

public int run(String[] args) throws Exception {
    Configuration conf = getConf();
    GenericOptionsParser parser = new GenericOptionsParser(conf, args);
    args = parser.getRemainingArgs();/*from  w ww  . j  a v  a 2s .c  o  m*/
    if (args.length != 1) {
        GenericOptionsParser.printGenericCommandUsage(System.out);

        truncate(getAdmin().listTableNamesByNamespace(MY_NAMESPACE));
        System.exit(2);
    }

    String importFile = args[0];
    FileSystem fs = null;
    BufferedReader br = null;
    Model m = null;

    try {
        fs = FileSystem.get(conf);
        Path path = new Path(importFile);
        br = new BufferedReader(new InputStreamReader(fs.open(path)));
        m = createModel();

        Stopwatch sw = new Stopwatch();
        sw.start();
        m.read(br, null, RDFLanguages.strLangNTriples);
        sw.stop();
        System.out.printf("Loading '%s' took %d.\n", importFile, sw.elapsedTime(TimeUnit.MILLISECONDS));
        sw.reset();
        sw.start();
        runTestQuery(m);
        sw.stop();
        System.out.printf("Query '%s' took %d.\n", query, sw.elapsedTime(TimeUnit.MILLISECONDS));
        sw.reset();
        sw.start();

        createStore(m);
        sw.stop();
        System.out.printf("loadHbase took %d.\n", sw.elapsedTime(TimeUnit.MILLISECONDS));
    } finally {
        if (m != null)
            m.close();
        if (br != null)
            br.close();
        if (fs != null)
            fs.close();
    }

    return 0;
}

From source file:org.apache.drill.exec.store.schedule.BlockMapBuilder.java

/**
 * For a given FileWork, calculate how many bytes are available on each on drillbit endpoint
 *
 * @param work the FileWork to calculate endpoint bytes for
 * @throws IOException//from www  . j  a va 2 s.c  o  m
 */
public EndpointByteMap getEndpointByteMap(FileWork work) throws IOException {
    Stopwatch watch = new Stopwatch();
    watch.start();
    Path fileName = new Path(work.getPath());

    ImmutableRangeMap<Long, BlockLocation> blockMap = getBlockMap(fileName);
    EndpointByteMapImpl endpointByteMap = new EndpointByteMapImpl();
    long start = work.getStart();
    long end = start + work.getLength();
    Range<Long> rowGroupRange = Range.closedOpen(start, end);

    // Find submap of ranges that intersect with the rowGroup
    ImmutableRangeMap<Long, BlockLocation> subRangeMap = blockMap.subRangeMap(rowGroupRange);

    // Iterate through each block in this submap and get the host for the block location
    for (Map.Entry<Range<Long>, BlockLocation> block : subRangeMap.asMapOfRanges().entrySet()) {
        String[] hosts;
        Range<Long> blockRange = block.getKey();
        try {
            hosts = block.getValue().getHosts();
        } catch (IOException ioe) {
            throw new RuntimeException("Failed to get hosts for block location", ioe);
        }
        Range<Long> intersection = rowGroupRange.intersection(blockRange);
        long bytes = intersection.upperEndpoint() - intersection.lowerEndpoint();

        // For each host in the current block location, add the intersecting bytes to the corresponding endpoint
        for (String host : hosts) {
            DrillbitEndpoint endpoint = getDrillBitEndpoint(host);
            if (endpoint != null) {
                endpointByteMap.add(endpoint, bytes);
            } else {
                logger.info("Failure finding Drillbit running on host {}.  Skipping affinity to that host.",
                        host);
            }
        }
    }

    logger.debug("FileWork group ({},{}) max bytes {}", work.getPath(), work.getStart(),
            endpointByteMap.getMaxBytes());

    logger.debug("Took {} ms to set endpoint bytes", watch.stop().elapsed(TimeUnit.MILLISECONDS));
    return endpointByteMap;
}

From source file:es.usc.citius.composit.cli.command.CompositionCommand.java

private void benchmark(ComposIT<Concept, Boolean> composit, WSCTest.Dataset dataset, int cycles) {
    // Compute benchmark
    String bestSample = null;//from  w  w w .j  av a 2s  .c  o  m
    Stopwatch watch = Stopwatch.createUnstarted();
    long minMS = Long.MAX_VALUE;
    for (int i = 0; i < cycles; i++) {
        System.out.println("[ComposIT Search] Starting benchmark cycle " + (i + 1));
        watch.start();
        composit.search(dataset.getRequest());
        long ms = watch.stop().elapsed(TimeUnit.MILLISECONDS);
        if (ms < minMS) {
            minMS = ms;
        }
        watch.reset();

        if (cli.isMetrics()) {
            cli.println(" > Metrics: ");
            cli.println(" METRICS NOT IMPLEMENTED");
        }
    }
    System.out.println(
            "[Benchmark Result] " + cycles + "-cycle benchmark completed. Best time: " + minMS + " ms.");
    if (cli.isMetrics() && bestSample != null) {
        cli.println("Best sample: " + bestSample);
    }
}

From source file:org.apache.drill.exec.store.hbase.HBaseRecordReader.java

@Override
public int next() {
    Stopwatch watch = new Stopwatch();
    watch.start();
    if (rowKeyVector != null) {
        rowKeyVector.clear();//www  .  j  av  a2 s .c  o  m
        rowKeyVector.allocateNew();
    }
    for (ValueVector v : familyVectorMap.values()) {
        v.clear();
        v.allocateNew();
    }

    int rowCount = 0;
    done: for (; rowCount < TARGET_RECORD_COUNT; rowCount++) {
        Result result = null;
        try {
            if (operatorContext != null) {
                operatorContext.getStats().startWait();
            }
            try {
                result = resultScanner.next();
            } finally {
                if (operatorContext != null) {
                    operatorContext.getStats().stopWait();
                }
            }
        } catch (IOException e) {
            throw new DrillRuntimeException(e);
        }
        if (result == null) {
            break done;
        }

        // parse the result and populate the value vectors
        Cell[] cells = result.rawCells();
        if (rowKeyVector != null) {
            rowKeyVector.getMutator().setSafe(rowCount, cells[0].getRowArray(), cells[0].getRowOffset(),
                    cells[0].getRowLength());
        }
        if (!rowKeyOnly) {
            for (Cell cell : cells) {
                int familyOffset = cell.getFamilyOffset();
                int familyLength = cell.getFamilyLength();
                byte[] familyArray = cell.getFamilyArray();
                MapVector mv = getOrCreateFamilyVector(new String(familyArray, familyOffset, familyLength),
                        true);

                int qualifierOffset = cell.getQualifierOffset();
                int qualifierLength = cell.getQualifierLength();
                byte[] qualifierArray = cell.getQualifierArray();
                NullableVarBinaryVector v = getOrCreateColumnVector(mv,
                        new String(qualifierArray, qualifierOffset, qualifierLength));

                int valueOffset = cell.getValueOffset();
                int valueLength = cell.getValueLength();
                byte[] valueArray = cell.getValueArray();
                v.getMutator().setSafe(rowCount, valueArray, valueOffset, valueLength);
            }
        }
    }

    setOutputRowCount(rowCount);
    logger.debug("Took {} ms to get {} records", watch.elapsed(TimeUnit.MILLISECONDS), rowCount);
    return rowCount;
}

From source file:org.jetbrains.android.inspections.lint.DomPsiConverter.java

/**
 * Convert the given {@link XmlFile} to a DOM tree
 *
 * @param xmlFile the file to be converted
 * @return a corresponding W3C DOM tree//from   www .  j  a  v a2 s . c om
 */
@Nullable
public static Document convert(@NotNull XmlFile xmlFile) {
    try {
        XmlDocument xmlDocument = xmlFile.getDocument();
        if (xmlDocument == null) {
            return null;
        }

        @SuppressWarnings("UnusedAssignment")
        Stopwatch timer;
        if (BENCHMARK) {
            timer = new Stopwatch();
            timer.start();
        }

        Document document = convert(xmlDocument);

        if (BENCHMARK) {
            timer.stop();
            //noinspection UseOfSystemOutOrSystemErr
            System.out.println("Creating PSI for " + xmlFile.getName() + " took " + timer.elapsedMillis()
                    + "ms (" + timer.toString() + ")");
        }

        return document;
    } catch (Exception e) {
        String path = xmlFile.getName();
        VirtualFile virtualFile = xmlFile.getVirtualFile();
        if (virtualFile != null) {
            path = virtualFile.getPath();
        }
        throw new RuntimeException("Could not convert file " + path, e);
    }
}

From source file:ezbake.groups.service.caching.RedisCacheLayer.java

private Stopwatch getStopwatch() {
    Stopwatch watch = Stopwatch.createUnstarted();
    if (shouldLogTimers) {
        watch.start();
    }/*w ww  . jav  a2s  .c o m*/
    return watch;
}

From source file:org.apache.twill.internal.logging.KafkaAppender.java

/**
 * Publishes buffered logs to Kafka, within the given timeout.
 *
 * @return Number of logs published./*from w  ww . ja  v a 2  s .com*/
 * @throws TimeoutException If timeout reached before publish completed.
 */
private int publishLogs(long timeout, TimeUnit timeoutUnit) throws TimeoutException {
    List<ByteBuffer> logs = Lists.newArrayListWithExpectedSize(bufferedSize.get());

    for (String json : Iterables.consumingIterable(buffer)) {
        logs.add(Charsets.UTF_8.encode(json));
    }

    long backOffTime = timeoutUnit.toNanos(timeout) / 10;
    if (backOffTime <= 0) {
        backOffTime = 1;
    }

    try {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.start();
        long publishTimeout = timeout;

        do {
            try {
                int published = doPublishLogs(logs).get(publishTimeout, timeoutUnit);
                bufferedSize.addAndGet(-published);
                return published;
            } catch (ExecutionException e) {
                addError("Failed to publish logs to Kafka.", e);
                TimeUnit.NANOSECONDS.sleep(backOffTime);
                publishTimeout -= stopwatch.elapsedTime(timeoutUnit);
                stopwatch.reset();
                stopwatch.start();
            }
        } while (publishTimeout > 0);
    } catch (InterruptedException e) {
        addWarn("Logs publish to Kafka interrupted.", e);
    }
    return 0;
}

From source file:co.cask.cdap.gateway.router.handlers.SecurityAuthenticationHttpHandler.java

/**
 *
 * @param externalAuthenticationURIs the list that should be populated with discovered with
 *                                   external auth servers URIs
 * @throws Exception//from w  ww  .j  av a  2  s. c o  m
 */
private void stopWatchWait(JsonArray externalAuthenticationURIs) throws Exception {
    boolean done = false;
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.start();
    String protocol;
    int port;
    if (configuration.getBoolean(Constants.Security.SSL_ENABLED)) {
        protocol = "https";
        port = configuration.getInt(Constants.Security.AuthenticationServer.SSL_PORT);
    } else {
        protocol = "http";
        port = configuration.getInt(Constants.Security.AUTH_SERVER_BIND_PORT);
    }

    do {
        for (Discoverable d : discoverables) {
            String url = String.format("%s://%s:%d/%s", protocol, d.getSocketAddress().getHostName(), port,
                    GrantAccessToken.Paths.GET_TOKEN);
            externalAuthenticationURIs.add(new JsonPrimitive(url));
            done = true;
        }
        if (!done) {
            TimeUnit.MILLISECONDS.sleep(200);
        }
    } while (!done && stopwatch.elapsedTime(TimeUnit.SECONDS) < 2L);
}

From source file:com.flipkart.foxtrot.core.querystore.impl.ElasticsearchQueryStore.java

@Override
public void save(String table, Document document) throws QueryStoreException {
    table = ElasticsearchUtils.getValidTableName(table);
    try {// w w w  .java  2s .  c o  m
        if (!tableMetadataManager.exists(table)) {
            throw new QueryStoreException(QueryStoreException.ErrorCode.NO_SUCH_TABLE,
                    "No table exists with the name: " + table);
        }
        if (new DateTime().plusDays(1).minus(document.getTimestamp()).getMillis() < 0) {
            return;
        }
        dataStore.save(tableMetadataManager.get(table), document);
        long timestamp = document.getTimestamp();
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.start();
        connection.getClient().prepareIndex().setIndex(ElasticsearchUtils.getCurrentIndex(table, timestamp))
                .setType(ElasticsearchUtils.TYPE_NAME).setId(document.getId())
                .setTimestamp(Long.toString(timestamp)).setSource(mapper.writeValueAsBytes(document.getData()))
                .setConsistencyLevel(WriteConsistencyLevel.QUORUM).execute().get(2, TimeUnit.SECONDS);
        logger.info(String.format("ES took : %d table : %s", stopwatch.elapsedMillis(), table));
    } catch (QueryStoreException ex) {
        throw ex;
    } catch (DataStoreException ex) {
        DataStoreException.ErrorCode code = ex.getErrorCode();
        if (code.equals(DataStoreException.ErrorCode.STORE_INVALID_REQUEST)
                || code.equals(DataStoreException.ErrorCode.STORE_INVALID_DOCUMENT)) {
            throw new QueryStoreException(QueryStoreException.ErrorCode.INVALID_REQUEST, ex.getMessage(), ex);
        } else {
            throw new QueryStoreException(QueryStoreException.ErrorCode.DOCUMENT_SAVE_ERROR, ex.getMessage(),
                    ex);
        }
    } catch (JsonProcessingException ex) {
        throw new QueryStoreException(QueryStoreException.ErrorCode.INVALID_REQUEST, ex.getMessage(), ex);
    } catch (Exception ex) {
        throw new QueryStoreException(QueryStoreException.ErrorCode.DOCUMENT_SAVE_ERROR, ex.getMessage(), ex);
    }
}