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.facebook.presto.split.NativeSplitManager.java

@Override
public Iterable<Split> getPartitionSplits(TableHandle tableHandle, List<Partition> partitions) {
    Stopwatch splitTimer = new Stopwatch();
    splitTimer.start();/*from  w ww  .j a  va2  s .  c o m*/

    checkNotNull(partitions, "partitions is null");
    if (partitions.isEmpty()) {
        return ImmutableList.of();
    }

    Map<String, Node> nodesById = uniqueIndex(nodeManager.getAllNodes().getActiveNodes(),
            Node.getIdentifierFunction());

    List<Split> splits = new ArrayList<>();

    Multimap<Long, Entry<Long, String>> partitionShardNodes = shardManager
            .getCommittedPartitionShardNodes(tableHandle);

    for (Partition partition : partitions) {
        checkArgument(partition instanceof NativePartition, "Partition must be a native partition");
        NativePartition nativePartition = (NativePartition) partition;

        ImmutableMultimap.Builder<Long, String> shardNodes = ImmutableMultimap.builder();
        for (Entry<Long, String> partitionShardNode : partitionShardNodes
                .get(nativePartition.getNativePartitionId())) {
            shardNodes.put(partitionShardNode.getKey(), partitionShardNode.getValue());
        }

        for (Map.Entry<Long, Collection<String>> entry : shardNodes.build().asMap().entrySet()) {
            List<HostAddress> addresses = getAddressesForNodes(nodesById, entry.getValue());
            checkState(addresses.size() > 0, "no host for shard %s found", entry.getKey());
            Split split = new NativeSplit(entry.getKey(), addresses);
            splits.add(split);
        }
    }

    log.debug("Split retrieval for %d partitions (%d splits): %dms", partitions.size(), splits.size(),
            splitTimer.elapsed(TimeUnit.MILLISECONDS));

    // the query engine assumes that splits are returned in a somewhat random fashion. The native split manager,
    // because it loads the data from a db table will return the splits somewhat ordered by node id so only a sub
    // set of nodes is fired up. Shuffle the splits to ensure random distribution.
    Collections.shuffle(splits);

    return ImmutableList.copyOf(splits);
}

From source file:fr.ippon.wip.transformers.JSTransformer.java

/**
 * Transform the given Javascript code: rewrite Ajax URLs and regular URLs
 * defined in the portlet configuration.
 * /*  ww  w .  j  ava  2 s  .c om*/
 * @param input
 *            the string corresponding to the original JavaScript code
 * @return a string corresponding to the transformed JavaScript code
 * @throws TransformerException
 */
public String transform(String input) throws SAXException, IOException, TransformerException {
    super.transform(input);
    Stopwatch stopwatch = new Stopwatch().start();

    String url;

    // CUSTOM
    // ------------------------------------------------------------------

    // ---------------------------------------------------------------------------

    Map<String, PostRequestBuilder.ResourceType> jsUrls = wipConfig.getJavascriptResourcesMap();
    for (String jsUrl : jsUrls.keySet()) {
        url = jsUrl;
        // Add \\ for regex characters like "?"
        if (url.contains("?"))
            url = url.replace("?", "\\?");
        // Rewrite accoding to the URL type
        input = input.replaceAll(url,
                urlFactory.createProxyUrl(jsUrl, "GET", jsUrls.get(jsUrl).name(), response));
    }

    // Rewriting URLs
    String regex = wipConfig.getJsRegex();
    input = rewrite(regex, input);

    input = transformAjaxJQuery(input);

    timeProcess.set(stopwatch.elapsedMillis());
    return input;
}

From source file:com.madgag.agit.FileListFragment.java

@Override
public Loader<List<FilePath>> onCreateLoader(int id, Bundle args) {
    return new AsyncLoader<List<FilePath>>(getActivity()) {
        public List<FilePath> loadInBackground() {

            try {
                Bundle args = getArguments();
                Repository repo = new FileRepository(args.getString(GITDIR));
                RevCommit commit = new RevWalk(repo).parseCommit(repo.resolve(args.getString(REVISION)));

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

                final List<FilePath> paths = newArrayList();
                TreeWalk treeWalk = new TreeWalk(repo);
                treeWalk.setRecursive(true);
                treeWalk.addTree(commit.getTree());

                while (treeWalk.next()) {
                    paths.add(new FilePath(treeWalk.getRawPath()));
                }//from   ww  w .  j  a  v a 2 s . c  o m
                Log.d(TAG, "Found " + paths.size() + " files " + stopwatch.stop());

                new Thread(new Runnable() {
                    @Override
                    public void run() { // knocks around 15-30% off time-to-display the list
                        Stopwatch stopwatch = new Stopwatch().start();
                        for (FilePath filePath : paths) {
                            filePath.getPath();
                        }
                        Log.d(TAG,
                                "Converted " + paths.size() + " path byte buffs to string " + stopwatch.stop());
                    }
                }).start();
                return paths;
            } catch (Exception e) {
                Log.w(TAG, "Bang", e);
                throw new RuntimeException(e);
            }
        }
    };
}

From source file:org.apache.provisionr.test.ProvisionrLiveTestSupport.java

public void waitForProcessEnd(final String processInstanceId, int timeoutInMilliseconds) throws Exception {
    Stopwatch stopwatch = new Stopwatch().start();
    while (isProcessNotEnded(processInstanceId)) {
        if (stopwatch.elapsedMillis() > timeoutInMilliseconds) {
            throw new TimeoutException(String.format("Process %s not ended in %d milliseconds.",
                    processInstanceId, timeoutInMilliseconds));
        }/*from   w  w  w .  ja va  2 s .  c om*/
        LOG.info(String.format("Process instance %s not ended. Waiting 1s.", processInstanceId));
        TimeUnit.SECONDS.sleep(1);
    }
    LOG.info(String.format("Process instance %s ended as expected in less than %d milliseconds",
            processInstanceId, timeoutInMilliseconds));
}

From source file:org.geogit.api.plumbing.WriteTree2.java

/**
 * Executes the write tree operation.//  www.  jav a  2  s  .  c  om
 * 
 * @return the new root tree id, the current HEAD tree id if there are no differences between
 *         the index and the HEAD, or {@code null} if the operation has been cancelled (as
 *         indicated by the {@link #getProgressListener() progress listener}.
 */
@Override
public ObjectId call() {
    Stopwatch sw = new Stopwatch().start();

    final ProgressListener progress = getProgressListener();

    TreeDifference treeDifference = computeTreeDifference();

    if (treeDifference.areEqual()) {
        MutableTree leftTree = treeDifference.getLeftTree();
        Node leftNode = leftTree.getNode();
        ObjectId leftOid = leftNode.getObjectId();
        return leftOid;
    }

    final MutableTree oldLeftTree = treeDifference.getLeftTree().clone();
    Preconditions.checkState(oldLeftTree.equals(treeDifference.getLeftTree()));

    // handle renames before new and deleted trees for the computation of new and deleted to be
    // accurate
    Set<String> ignoreList = Sets.newHashSet();
    handleRenames(treeDifference, ignoreList);
    handlePureMetadataChanges(treeDifference, ignoreList);
    handleNewTrees(treeDifference, ignoreList);
    handleDeletedTrees(treeDifference, ignoreList);
    handleRemainingDifferences(treeDifference, ignoreList);

    progress.complete();

    MutableTree newLeftTree = treeDifference.getLeftTree();

    final RevTree newRoot = newLeftTree.build(getIndex().getDatabase(), repositoryDatabase);

    ObjectId newRootId = newRoot.getId();

    sw.stop();
    LOGGER.debug("WriteTree2 took {}", sw);
    return newRootId;
}

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

@Override
public void sort(final VectorContainer container) {
    final Stopwatch watch = new Stopwatch();
    watch.start();//w  ww  .j a  v  a 2s. co m
    while (runStarts.size() > 1) {

        // check if we're cancelled/failed frequently
        if (!context.shouldContinue()) {
            return;
        }

        int outIndex = 0;
        newRunStarts = Queues.newLinkedBlockingQueue();
        newRunStarts.add(outIndex);
        final int size = runStarts.size();
        for (int i = 0; i < size / 2; i++) {
            final int left = runStarts.poll();
            final int right = runStarts.poll();
            Integer end = runStarts.peek();
            if (end == null) {
                end = vector4.getTotalCount();
            }
            outIndex = merge(left, right, end, outIndex);
            if (outIndex < vector4.getTotalCount()) {
                newRunStarts.add(outIndex);
            }
        }
        if (outIndex < vector4.getTotalCount()) {
            copyRun(outIndex, vector4.getTotalCount());
        }
        final SelectionVector4 tmp = aux.createNewWrapperCurrent(desiredRecordBatchCount);
        aux.clear();
        aux = this.vector4.createNewWrapperCurrent(desiredRecordBatchCount);
        vector4.clear();
        this.vector4 = tmp.createNewWrapperCurrent(desiredRecordBatchCount);
        tmp.clear();
        runStarts = newRunStarts;
    }
    aux.clear();
}

From source file:fr.ippon.wip.http.hc.HttpClientDecorator.java

/**
 * This method://from   w  ww .ja  va2 s. c  o  m
 * <ul>
 * <li>invokes each pre-processor</li>
 * <li>delegate execution of the request to the backend HttpClient instance</li>
 * <li>invokes each post-processor</li>
 * </ul>
 */
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException {
    try {
        for (AbstractHttpRequestFilter filter : filters)
            if (!filter.filter(target, request, context))
                return AbstractHttpRequestFilter.NOT_FOUND_RESPONSE;

        for (HttpRequestInterceptor preProcessor : preProcessors) {
            preProcessor.process(request, context);
        }

        Stopwatch stopwatch = new Stopwatch().start();
        HttpResponse response = backend.execute(target, request, context);
        timeProcess.set(stopwatch.elapsedMillis());

        for (HttpResponseInterceptor postProcessor : postProcessors) {
            postProcessor.process(response, context);
        }

        return response;
    } catch (HttpException he) {
        throw new RuntimeException(he);
    }
}

From source file:org.rhq.server.metrics.MetricsServer.java

public Iterable<MeasurementDataNumericHighLowComposite> findDataForResource(int scheduleId, long beginTime,
        long endTime, int numberOfBuckets) {
    Stopwatch stopwatch = new Stopwatch().start();
    try {/*ww  w .ja v  a 2  s .  co  m*/
        DateTime begin = new DateTime(beginTime);

        if (dateTimeService.isInRawDataRange(begin)) {
            Iterable<RawNumericMetric> metrics = dao.findRawMetrics(scheduleId, beginTime, endTime);
            return createRawComposites(metrics, beginTime, endTime, numberOfBuckets);
        }

        List<AggregateNumericMetric> metrics = null;
        if (dateTimeService.isIn1HourDataRange(begin)) {
            metrics = dao.findAggregateMetrics(scheduleId, Bucket.ONE_HOUR, beginTime, endTime);
            return createComposites(metrics, beginTime, endTime, numberOfBuckets);
        } else if (dateTimeService.isIn6HourDataRange(begin)) {
            metrics = dao.findAggregateMetrics(scheduleId, Bucket.SIX_HOUR, beginTime, endTime);
            return createComposites(metrics, beginTime, endTime, numberOfBuckets);
        } else if (dateTimeService.isIn24HourDataRange(begin)) {
            metrics = dao.findAggregateMetrics(scheduleId, Bucket.TWENTY_FOUR_HOUR, beginTime, endTime);
            return createComposites(metrics, beginTime, endTime, numberOfBuckets);
        } else {
            throw new IllegalArgumentException("beginTime[" + beginTime + "] is outside the accepted range.");
        }
    } finally {
        stopwatch.stop();
        if (log.isDebugEnabled()) {
            log.debug("Finished calculating resource summary aggregate in "
                    + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
        }
    }
}

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

@Override
public void generate() throws SchemaChangeException {
    Stopwatch watch = new Stopwatch();
    watch.start();//from   w w w. j av  a  2s .  c om
    final DrillBuf drillBuf = allocator.buffer(4 * queueSize);
    finalSv4 = new SelectionVector4(drillBuf, queueSize, 4000);
    for (int i = queueSize - 1; i >= 0; i--) {
        finalSv4.set(i, pop());
    }
    logger.debug("Took {} us to generate output of {}", watch.elapsed(TimeUnit.MICROSECONDS),
            finalSv4.getTotalCount());
}

From source file:com.madgag.agit.LogFragment.java

@Override
public Loader<List<RevCommit>> onCreateLoader(int id, Bundle args) {
    return new AsyncLoader<List<RevCommit>>(getActivity()) {
        public List<RevCommit> loadInBackground() {
            Stopwatch stopwatch = new Stopwatch().start();
            Bundle args = getArguments();
            try {
                Repository repo = new FileRepository(args.getString(GITDIR));

                LogCommand log = new Git(repo).log();
                List<String> untilRevs = getArguments().getStringArrayList(UNTIL_REVS);
                if (untilRevs == null || untilRevs.isEmpty()) {
                    log.all();//from  w  w w  .  j  a  v  a  2 s  .c  o  m
                } else {
                    for (String untilRev : untilRevs) {
                        log.add(repo.resolve(untilRev));
                    }
                }

                List<RevCommit> sampleRevCommits = newArrayList(log.call());

                Log.d(TAG, "Found " + sampleRevCommits.size() + " commits " + stopwatch);

                return sampleRevCommits;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    };
}