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

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

Introduction

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

Prototype

@CheckReturnValue
public static Stopwatch createStarted() 

Source Link

Document

Creates (and starts) a new stopwatch using System#nanoTime as its time source.

Usage

From source file:com.facebook.buck.distributed.ServerContentsProvider.java

/** Blocking call */
private void makePeriodicMultiFetchRequest() {
    Stopwatch stopwatch = Stopwatch.createStarted();
    int numFilesFetched = this.processFileBuffer(false);
    long elapsedMs = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS);
    if (numFilesFetched > 0) {
        this.statsTracker.recordPeriodicCasMultiFetch(elapsedMs);
    }/* w w w .  j a v  a  2  s.  c  o  m*/
}

From source file:org.onosproject.cli.net.AddFlowsCommand.java

@Override
protected void execute() {

    FlowRuleService flowService = get(FlowRuleService.class);
    DeviceService deviceService = get(DeviceService.class);
    CoreService coreService = get(CoreService.class);

    ApplicationId appId = coreService.registerApplication("onos.test.flow.installer");

    int flowsPerDevice = Integer.parseInt(flows);
    int num = Integer.parseInt(numOfRuns);

    ArrayList<Long> results = Lists.newArrayList();
    Iterable<Device> devices = deviceService.getDevices();
    TrafficTreatment treatment = DefaultTrafficTreatment.builder()
            .setOutput(PortNumber.portNumber(RandomUtils.nextInt())).build();
    TrafficSelector.Builder sbuilder;//  www  .j  av  a2  s. co  m
    FlowRuleOperations.Builder rules = FlowRuleOperations.builder();
    FlowRuleOperations.Builder remove = FlowRuleOperations.builder();

    for (Device d : devices) {
        for (int i = 0; i < flowsPerDevice; i++) {
            sbuilder = DefaultTrafficSelector.builder();

            sbuilder.matchEthSrc(MacAddress.valueOf(RandomUtils.nextInt() * i))
                    .matchEthDst(MacAddress.valueOf((Integer.MAX_VALUE - i) * RandomUtils.nextInt()));

            int randomPriority = RandomUtils.nextInt();
            rules.add(
                    new DefaultFlowRule(d.id(), sbuilder.build(), treatment, randomPriority, appId, 10, false));
            remove.remove(
                    new DefaultFlowRule(d.id(), sbuilder.build(), treatment, randomPriority, appId, 10, false));

        }
    }

    for (int i = 0; i < num; i++) {

        latch = new CountDownLatch(2);
        flowService.apply(rules.build(new FlowRuleOperationsContext() {

            private final Stopwatch timer = Stopwatch.createStarted();

            @Override
            public void onSuccess(FlowRuleOperations ops) {

                timer.stop();
                results.add(timer.elapsed(TimeUnit.MILLISECONDS));
                if (results.size() == num) {
                    if (outputJson()) {
                        print("%s", json(new ObjectMapper(), true, results));
                    } else {
                        printTime(true, results);
                    }
                }
                latch.countDown();
            }
        }));

        flowService.apply(remove.build(new FlowRuleOperationsContext() {
            @Override
            public void onSuccess(FlowRuleOperations ops) {
                latch.countDown();
            }
        }));
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}

From source file:eu.numberfour.n4jsx.ui.editor.syntaxcoloring.HighlightingParser.java

private List<Token> doParse(CharStream in) {
    TokenSource tokenSource = createLexer(in);
    LazyTokenStream tokenStream = createTokenStream(tokenSource);
    setInitialHiddenTokens(tokenStream);
    InternalN4JSXParser parser = createParser(tokenStream);
    IUnorderedGroupHelper helper = unorderedGroupHelper.get();
    if (!(helper instanceof IUnorderedGroupHelper.Null)) {
        throw new IllegalStateException("Unexpected usage of unordered groups.");
    }/*from  www .j a v a2s . c  o m*/
    Stopwatch stopwatch = null;
    boolean debug = LOGGER.isDebugEnabled();
    // boolean debug = true;
    if (debug) {
        stopwatch = Stopwatch.createStarted();
    }
    try {
        parser.entryRuleIDLScript();
        while (tokenStream.LT(1) != Token.EOF_TOKEN) {
            tokenStream.consume();
        }
        @SuppressWarnings("unchecked")
        List<Token> result = tokenStream.getTokens();
        return result;
    } catch (Exception re) {
        throw new ParseException(re.getMessage(), re);
    } finally {
        if (debug) {
            assert stopwatch != null;
            long elapsed = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS);
            if (elapsed > 5) {
                LOGGER.warn("Coloring parser took: " + elapsed);
            }
        }
    }
}

From source file:com.minestellar.core.MinestellarCore.java

@EventHandler
public void init(FMLInitializationEvent event) {
    Stopwatch stopwatch = Stopwatch.createStarted();

    NetworkHandler.init();/*www .ja v  a 2s.co  m*/

    MinestellarCore.stellarBlocksTab = new MinestellarCreativeTab(CreativeTabs.getNextID(), "MinestellarBlocks",
            Item.getItemFromBlock(CoreBlocks.coreOreBlocks), 0);
    MinestellarCore.stellarItemsTab = new MinestellarCreativeTab(CreativeTabs.getNextID(), "MinestellarItems",
            CoreItems.coreBasicItems, 0);

    GameRegistry.registerWorldGenerator(new OverworldGenerator(CoreBlocks.coreOreBlocks, 0, 24, 0, 200, 7), 6);
    GameRegistry.registerWorldGenerator(new OverworldGenerator(CoreBlocks.coreOreBlocks, 1, 22, 0, 200, 7), 4);
    GameRegistry.registerWorldGenerator(new OverworldGenerator(CoreBlocks.coreOreBlocks, 2, 12, 0, 200, 3), 4);
    GameRegistry.registerWorldGenerator(new OverworldGenerator(CoreBlocks.coreOreBlocks, 3, 12, 0, 200, 3), 2);
    GameRegistry.registerWorldGenerator(new OverworldGenerator(CoreBlocks.coreOreBlocks, 4, 24, 0, 200, 7), 4);
    GameRegistry.registerWorldGenerator(new OverworldGenerator(CoreBlocks.coreOreBlocks, 5, 22, 0, 200, 7), 4);
    GameRegistry.registerWorldGenerator(new OverworldGenerator(CoreBlocks.coreOreBlocks, 6, 12, 0, 200, 3), 7);

    GameRegistry.registerWorldGenerator(new OverworldGenerator(CoreBlocks.oilFluidBlock, 0, 25, 20, 75, 3), 20);

    RecipeManagerCore.loadRecipes();

    this.registerTileEntities();
    this.registerCreatures();
    this.registerOtherEntities();

    NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler());

    MinestellarCore.proxy.init(event);

    log.info("Initialization Completed in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms.");
}

From source file:com.android.build.gradle.shrinker.FullRunShrinker.java

/**
 * Populates the graph with all nodes (classes, members) and edges (dependencies, references),
 * so that it's ready to be traversed in search of reachable ndoes.
 *///from   ww  w . j ava  2  s . co m
private void buildGraph(@NonNull Iterable<TransformInput> programInputs,
        @NonNull Iterable<TransformInput> libraryInputs) throws IOException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    final PostProcessingData<T> postProcessingData = new PostProcessingData<>();

    readPlatformJars();

    for (TransformInput input : libraryInputs) {
        for (File directory : getAllDirectories(input)) {
            for (final File classFile : getClassFiles(directory)) {
                mExecutor.execute(() -> {
                    processLibraryClass(Files.toByteArray(classFile));
                    return null;
                });
            }
        }

        for (final File jarFile : getAllJars(input)) {
            processJarFile(jarFile, this::processLibraryClass);
        }
    }

    for (TransformInput input : programInputs) {
        for (File directory : getAllDirectories(input)) {
            for (final File classFile : getClassFiles(directory)) {
                mExecutor.execute(new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        processProgramClassFile(Files.toByteArray(classFile), classFile, postProcessingData);
                        return null;
                    }
                });
            }
        }

        for (final File jarFile : getAllJars(input)) {
            processJarFile(jarFile, new ByteCodeConsumer() {
                @Override
                public void process(byte[] bytes) throws IOException {
                    processProgramClassFile(bytes, jarFile, postProcessingData);
                }
            });
        }
    }
    waitForAllTasks();
    logTime("Read input", stopwatch);

    handleOverrides(postProcessingData.getVirtualMethods());
    handleMultipleInheritance(postProcessingData.getMultipleInheritance());
    handleInterfaceInheritance(postProcessingData.getInterfaceInheritance());
    resolveReferences(postProcessingData.getUnresolvedReferences());
    waitForAllTasks();
    logTime("Finish graph", stopwatch);

    mGraph.checkDependencies(mShrinkerLogger);
}

From source file:org.apache.geode.internal.process.lang.AvailablePid.java

/**
 * Returns randomly unused pid between {@code lowerBound} (inclusive) and {@code upperBound}
 * (inclusive).//  w ww. j a  v a 2s .  c o m
 */
public int findAvailablePid() throws TimeoutException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    int pid = random();
    while (isProcessAlive(pid)) {
        if (stopwatch.elapsed(MILLISECONDS) > timeoutMillis) {
            throw new TimeoutException("Failed to find available pid within " + timeoutMillis + " millis.");
        }
        pid = random();
    }
    return pid;
}

From source file:com.dssmp.agent.tailing.FirehoseSender.java

@Override
protected BufferSendResult<FirehoseRecord> attemptSend(RecordBuffer<FirehoseRecord> buffer) {
    activeBatchPutCalls.incrementAndGet();
    IMetricsScope metrics = agentContext.beginScope();
    metrics.addDimension(Metrics.DESTINATION_DIMENSION, "DeliveryStream:" + getDestination());
    try {//from  w w w . j  a  v a 2s. c  om
        BufferSendResult<FirehoseRecord> sendResult = null;
        List<Record> requestRecords = new ArrayList<>();
        for (FirehoseRecord data : buffer) {
            Record record = new Record();
            record.setData(data.data());
            requestRecords.add(record);
        }
        PutRecordBatchRequest request = new PutRecordBatchRequest();
        request.setRecords(requestRecords);
        request.setDeliveryStreamName(getDestination());
        PutRecordBatchResult result = null;
        Stopwatch timer = Stopwatch.createStarted();
        totalBatchPutCalls.incrementAndGet();
        try {
            logger.trace("{}: Sending buffer {} to firehose {}...", flow.getId(), buffer, getDestination());
            metrics.addCount(RECORDS_ATTEMPTED_METRIC, requestRecords.size());
            result = agentContext.getFirehoseClient().putRecordBatch(request);
            metrics.addCount(SERVICE_ERRORS_METRIC, 0);
        } catch (AmazonServiceException e) {
            metrics.addCount(SERVICE_ERRORS_METRIC, 1);
            totalBatchPutServiceErrors.incrementAndGet();
            throw e;
        } catch (Exception e) {
            metrics.addCount(SERVICE_ERRORS_METRIC, 1);
            totalBatchPutOtherErrors.incrementAndGet();
            throw e;
        } finally {
            totalBatchPutLatency.addAndGet(timer.elapsed(TimeUnit.MILLISECONDS));
        }
        if (sendResult == null) {
            List<Integer> sentRecords = new ArrayList<>(requestRecords.size());
            Multiset<String> errors = HashMultiset.<String>create();
            int index = 0;
            long totalBytesSent = 0;
            for (PutRecordBatchResponseEntry responseEntry : result.getRequestResponses()) {
                Record record = requestRecords.get(index);
                if (responseEntry.getErrorCode() == null) {
                    sentRecords.add(index);
                    totalBytesSent += record.getData().limit();
                } else {
                    logger.trace("{}:{} Record {} returned error code {}: {}", flow.getId(), buffer, index,
                            responseEntry.getErrorCode(), responseEntry.getErrorMessage());
                    errors.add(responseEntry.getErrorCode());
                }
                ++index;
            }
            if (sentRecords.size() == requestRecords.size()) {
                sendResult = BufferSendResult.succeeded(buffer);
            } else {
                buffer = buffer.remove(sentRecords);
                sendResult = BufferSendResult.succeeded_partially(buffer, requestRecords.size());
            }
            metrics.addData(BYTES_SENT_METRIC, totalBytesSent, StandardUnit.Bytes);
            int failedRecordCount = requestRecords.size() - sentRecords.size();
            metrics.addCount(RECORD_ERRORS_METRIC, failedRecordCount);
            logger.debug("{}:{} Records sent firehose {}: {}. Failed records: {}", flow.getId(), buffer,
                    getDestination(), sentRecords.size(), failedRecordCount);
            totalRecordsAttempted.addAndGet(requestRecords.size());
            totalRecordsSent.addAndGet(sentRecords.size());
            totalRecordsFailed.addAndGet(failedRecordCount);

            if (logger.isDebugEnabled() && !errors.isEmpty()) {
                synchronized (totalErrors) {
                    StringBuilder strErrors = new StringBuilder();
                    for (Multiset.Entry<String> err : errors.entrySet()) {
                        AtomicLong counter = totalErrors.get(err.getElement());
                        if (counter == null)
                            totalErrors.put(err.getElement(), counter = new AtomicLong());
                        counter.addAndGet(err.getCount());
                        if (strErrors.length() > 0)
                            strErrors.append(", ");
                        strErrors.append(err.getElement()).append(": ").append(err.getCount());
                    }
                    logger.debug("{}:{} Errors from firehose {}: {}", flow.getId(), buffer,
                            flow.getDestination(), strErrors.toString());
                }
            }
        }
        return sendResult;
    } finally {
        metrics.commit();
        activeBatchPutCalls.decrementAndGet();
    }
}

From source file:de.metas.ui.web.session.FixedMapSessionRepository.java

public void purgeExpiredSessions() {
    final Stopwatch stopwatch = Stopwatch.createStarted();
    int countExpiredSessions = 0;

    final List<ExpiringSession> sessionsToCheck = new ArrayList<>(sessions.values());
    for (final ExpiringSession session : sessionsToCheck) {
        if (session.isExpired()) {
            deleteAndFireEvent(session.getId(), true /* expired */);
            countExpiredSessions++;//from   ww  w  . j a  va2  s .co  m
        }
    }

    logger.debug("Purged {}/{} expired sessions in {}", countExpiredSessions, sessionsToCheck.size(),
            stopwatch);
}

From source file:org.grouplens.lenskit.knn.item.model.NormalizingItemItemModelBuilder.java

@SuppressWarnings("deprecation")
@Override//  w  ww.  j  a  v  a2  s .c o m
public SimilarityMatrixModel get() {
    logger.debug("building item-item model");

    LongSortedSet itemUniverse = buildContext.getItems();

    final int nitems = itemUniverse.size();

    LongKeyDomain itemDomain = LongKeyDomain.fromCollection(itemUniverse, true);
    assert itemDomain.size() == itemDomain.domainSize();
    assert itemDomain.domainSize() == nitems;
    List<List<ScoredId>> matrix = Lists.newArrayListWithCapacity(itemDomain.domainSize());

    // working space for accumulating each row (reuse between rows)
    MutableSparseVector currentRow = MutableSparseVector.create(itemUniverse);
    Stopwatch timer = Stopwatch.createStarted();

    for (int i = 0; i < nitems; i++) {
        assert matrix.size() == i;
        final long rowItem = itemDomain.getKey(i);
        final SparseVector vec1 = buildContext.itemVector(rowItem);

        // Take advantage of sparsity if we can
        LongIterator neighbors = iterationStrategy.neighborIterator(buildContext, rowItem, false);
        currentRow.fill(0);

        // Compute similarities and populate the vector
        while (neighbors.hasNext()) {
            final long colItem = neighbors.nextLong();
            final SparseVector vec2 = buildContext.itemVector(colItem);
            assert currentRow.containsKey(colItem);
            currentRow.set(colItem, similarity.similarity(rowItem, vec1, colItem, vec2));
        }

        // Remove the current item (it is not its own neighbor)
        currentRow.unset(rowItem);

        // Normalize and truncate the row
        MutableSparseVector normalized = rowNormalizer.normalize(rowItem, currentRow, null);
        truncator.truncate(normalized);

        // Build up and save the row
        ScoredIdListBuilder bld = new ScoredIdListBuilder(normalized.size());
        // TODO Allow the symbols in use to be customized
        List<ScoredId> row = bld.addChannels(normalized.getChannelVectorSymbols())
                .addTypedChannels(normalized.getChannelSymbols())
                .addAll(ScoredIds.collectionFromVector(normalized)).sort(ScoredIds.scoreOrder().reverse())
                .finish();
        matrix.add(row);
    }

    timer.stop();
    logger.info("built model for {} items in {}", nitems, timer);

    return new SimilarityMatrixModel(itemDomain, matrix);
}

From source file:com.smithsmodding.smithscore.SmithsCore.java

@Mod.EventHandler
public void postInit(FMLPostInitializationEvent event) {
    Stopwatch watch = Stopwatch.createStarted();

    watch.stop();/*ww  w .  ja  va2 s  .c  om*/

    Long milliseconds = watch.elapsed(TimeUnit.MILLISECONDS);
    getLogger().info(CoreReferences.LogMarkers.POSTINIT,
            "SmithsCore Post-Init completed after: " + milliseconds + " ms.");
}