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

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

Introduction

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

Prototype

@CheckReturnValue
public long elapsed(TimeUnit desiredUnit) 

Source Link

Document

Returns the current elapsed time shown on this stopwatch, expressed in the desired time unit, with any fraction rounded down.

Usage

From source file:com.arpnetworking.metrics.mad.performance.FilePerfTestBase.java

/**
 * Runs a filter./*from w  w  w  . j ava2s  .com*/
 *
 * @param pipelineConfigurationFile Pipeline configuration file.
 * @param duration Timeout period.
 * @param variables Substitution key-value pairs into pipeline configuration file.
 * @throws IOException if configuration cannot be loaded.
 */
protected void benchmark(final String pipelineConfigurationFile, final Duration duration,
        final ImmutableMap<String, String> variables) throws IOException {
    // Replace any variables in the configuration file
    String configuration = Resources.toString(Resources.getResource(pipelineConfigurationFile), Charsets.UTF_8);
    for (final Map.Entry<String, String> entry : variables.entrySet()) {
        configuration = configuration.replace(entry.getKey(), entry.getValue());
    }

    // Load the specified stock configuration
    final PipelineConfiguration stockPipelineConfiguration = new StaticConfiguration.Builder()
            .addSource(new JsonNodeLiteralSource.Builder().setSource(configuration).build())
            .setObjectMapper(PipelineConfiguration.createObjectMapper(_injector)).build()
            .getRequiredAs(PipelineConfiguration.class);

    // Canary tracking
    LOGGER.info(String.format("Expected canaries; periods=%s", stockPipelineConfiguration.getPeriods()));
    final CountDownLatch latch = new CountDownLatch(stockPipelineConfiguration.getPeriods().size());
    final Set<Period> periods = Sets.newConcurrentHashSet();

    // Create custom "canary" sink
    final ListeningSink sink = new ListeningSink((periodicData) -> {
        if (periodicData != null) {
            for (final String metricName : periodicData.getData().keys()) {
                if (TestFileGenerator.CANARY.equals(metricName)) {
                    if (periods.add(periodicData.getPeriod())) {
                        LOGGER.info(String.format("Canary flew; filter=%s, period=%s", this.getClass(),
                                periodicData.getPeriod()));
                        latch.countDown();
                    }
                }
            }
        }
        return null;
    });

    // Add the custom "canary" sink
    final List<Sink> benchmarkSinks = Lists.newArrayList(stockPipelineConfiguration.getSinks());
    benchmarkSinks.add(sink);

    // Create the custom configuration
    final PipelineConfiguration benchmarkPipelineConfiguration = OvalBuilder.<PipelineConfiguration, PipelineConfiguration.Builder>clone(
            stockPipelineConfiguration).setSinks(benchmarkSinks).build();

    // Instantiate the pipeline
    final Pipeline pipeline = new Pipeline(benchmarkPipelineConfiguration);

    // Execute the pipeline until the canary flies the coop
    try {
        LOGGER.debug(String.format("Launching pipeline; configuration=%s", pipelineConfigurationFile));
        final Stopwatch timer = Stopwatch.createUnstarted();
        timer.start();
        pipeline.launch();

        if (!latch.await(duration.getMillis(), TimeUnit.MILLISECONDS)) {
            LOGGER.error("Test timed out");
            throw new RuntimeException("Test timed out");
        }

        timer.stop();
        LOGGER.info(String.format("Performance filter result; filter=%s, seconds=%s", this.getClass(),
                timer.elapsed(TimeUnit.SECONDS)));

    } catch (final InterruptedException e) {
        Thread.interrupted();
        throw new RuntimeException("Test interrupted");
    } finally {
        pipeline.shutdown();
    }
}

From source file:org.eclipse.viatra.modelobfuscator.application.common.ModelObfuscatorHeadless.java

/**
 * @param obfuscatorBuilder/*from  w w w  .  j  a  va  2s  . c  om*/
 */
private void performObfuscation(EMFModelObfuscatorBuilder obfuscatorBuilder) {
    SimpleEMFModelObfuscator obfuscator = obfuscatorBuilder.build();
    System.out.println("Obfuscating EMF resource set");
    Stopwatch stopwatch = Stopwatch.createStarted();
    obfuscator.obfuscate();
    stopwatch.stop();
    String elapsedTime = stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms ("
            + stopwatch.elapsed(TimeUnit.NANOSECONDS) + " ns)";
    System.out.println("Obfuscation finished in: " + elapsedTime);
}

From source file:com.facebook.buck.cli.DistBuildKillCommand.java

@Override
public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception {
    Console console = params.getConsole();
    PrintStream stdout = console.getStdOut();
    StampedeId stampedeId = getStampedeId();

    try (DistBuildService service = DistBuildFactory.newDistBuildService(params)) {
        stdout.println(String.format("Fetching build information for StampedeId=[%s].", stampedeId.getId()));
        Stopwatch stopwatch = Stopwatch.createStarted();
        BuildJob buildJob = service.getCurrentBuildJobState(getStampedeId());

        stdout.println(String.format("The build is currently in status [%s:%s].",
                buildJob.getStatus().toString(), buildJob.getStatusMessage()));
        if (BuildStatusUtil.isTerminalBuildStatus(buildJob.getStatus())) {
            console.printSuccess(/*from   w ww .j  a  v a  2s .  c  o  m*/
                    String.format("Build is already finished so doing nothing. Took [%d millis] to execute.",
                            stopwatch.elapsed(TimeUnit.MILLISECONDS)));
            // Returning SUCCESS instead of NOTHING_TO_DO to possibly avoid breaking some contract
            return ExitCode.SUCCESS;
        }

        String statusMessage = String.format(
                "Build killed via 'buck distbuild kill' command by user=[%s] from host=[%s].",
                System.getProperty("user.name"), HostnameFetching.getHostname());
        stdout.println(String.format("Killing the build and setting statusMessage to [%s].", statusMessage));

        service.setFinalBuildStatus(stampedeId, BuildStatus.FAILED, statusMessage);
        console.printSuccess(String.format("Successfully killed the build in [%d millis].",
                stopwatch.elapsed(TimeUnit.MILLISECONDS)));
        return ExitCode.SUCCESS;
    }
}

From source file:it.anyplace.sync.discovery.utils.AddressRanker.java

private int doTestTcpConnection(SocketAddress socketAddress) {
    logger.debug("test tcp connection to address = {}", socketAddress);
    Stopwatch stopwatch = Stopwatch.createStarted();
    try (Socket socket = new Socket()) {
        socket.setSoTimeout(TCP_CONNECTION_TIMEOUT);
        socket.connect(socketAddress, TCP_CONNECTION_TIMEOUT);
    } catch (IOException ex) {
        logger.debug("address unreacheable = {} ({})", socketAddress, ex.toString());
        logger.trace("address unreacheable", ex);
        return -1;
    }//from  w ww .  j  av a  2s .  c  o  m
    int time = (int) stopwatch.elapsed(TimeUnit.MILLISECONDS);
    logger.debug("tcp connection to address = {} is ok, time = {} ms", socketAddress, time);
    return time;
}

From source file:com.palantir.atlasdb.cli.command.SweepCommand.java

@Override
public int execute(final AtlasDbServices services) {
    SweepTaskRunner sweepRunner = services.getSweepTaskRunner();

    if (!((namespace != null) ^ (table != null) ^ sweepAllTables)) {
        System.err.println("Specify one of --namespace, --table, or --all options.");
        return 1;
    }// w w w .  j a  va  2  s .  co  m
    if ((namespace != null) && (row != null)) {
        System.err.println("Cannot specify a start row (" + row
                + ") when sweeping multiple tables (in namespace " + namespace + ")");
        return 1;
    }

    Map<TableReference, Optional<byte[]>> tableToStartRow = Maps.newHashMap();

    if ((table != null)) {
        Optional<byte[]> startRow = Optional.of(new byte[0]);
        if (row != null) {
            startRow = Optional.of(decodeStartRow(row));
        }
        tableToStartRow.put(TableReference.createUnsafe(table), startRow);
    } else if (namespace != null) {
        Set<TableReference> tablesInNamespace = services.getKeyValueService().getAllTableNames().stream()
                .filter(tableRef -> tableRef.getNamespace().getName().equals(namespace))
                .collect(Collectors.toSet());
        for (TableReference table : tablesInNamespace) {
            tableToStartRow.put(table, Optional.of(new byte[0]));
        }
    } else if (sweepAllTables) {
        tableToStartRow.putAll(Maps.asMap(Sets.difference(services.getKeyValueService().getAllTableNames(),
                AtlasDbConstants.hiddenTables), Functions.constant(Optional.of(new byte[0]))));
    }

    for (Map.Entry<TableReference, Optional<byte[]>> entry : tableToStartRow.entrySet()) {
        final TableReference table = entry.getKey();
        Optional<byte[]> startRow = entry.getValue();

        final AtomicLong cellsExamined = new AtomicLong();
        final AtomicLong cellsDeleted = new AtomicLong();

        while (startRow.isPresent()) {
            Stopwatch watch = Stopwatch.createStarted();
            SweepResults results = sweepRunner.run(table, batchSize, startRow.get());
            System.out.println(String.format(
                    "Swept from %s to %s in table %s in %d ms, examined %d unique cells, deleted %d cells.",
                    encodeStartRow(startRow), encodeEndRow(results.getNextStartRow()), table,
                    watch.elapsed(TimeUnit.MILLISECONDS), results.getCellsExamined(),
                    results.getCellsDeleted()));
            startRow = results.getNextStartRow();
            cellsDeleted.addAndGet(results.getCellsDeleted());
            cellsExamined.addAndGet(results.getCellsExamined());
            maybeSleep();
        }

        services.getTransactionManager().runTaskWithRetry((TxTask) t -> {
            SweepPriorityTable priorityTable = SweepTableFactory.of().getSweepPriorityTable(t);
            SweepPriorityTable.SweepPriorityRow row1 = SweepPriorityTable.SweepPriorityRow
                    .of(table.getQualifiedName());
            priorityTable.putWriteCount(row1, 0L);
            priorityTable.putCellsDeleted(row1, cellsDeleted.get());
            priorityTable.putCellsExamined(row1, cellsExamined.get());
            priorityTable.putLastSweepTime(row1, System.currentTimeMillis());

            System.out
                    .println(String.format("Finished sweeping %s, examined %d unique cells, deleted %d cells.",
                            table, cellsExamined.get(), cellsDeleted.get()));

            if (cellsDeleted.get() > 0) {
                Stopwatch watch = Stopwatch.createStarted();
                services.getKeyValueService().compactInternally(table);
                System.out.println(String.format("Finished performing compactInternally on %s in %d ms.", table,
                        watch.elapsed(TimeUnit.MILLISECONDS)));
            }
            return null;
        });
    }
    return 0;
}

From source file:com.google.api.ads.adwords.jaxws.extensions.downloader.MultipleClientReportDownloader.java

/**
 * Downloads the specified report for all specified CIDs. Prints out list of failed CIDs. Returns
 * List<File> for all successful downloads.
 *
 * @param reportDefinition Report to download.
 * @param cids CIDs to download the report for.
 * @return Collection of File objects reports have been downloaded to.
 * @throws InterruptedException error trying to stop downloader thread.
 */// w ww .  j av  a 2  s . c  om
public Collection<File> downloadReports(final AdWordsSession.Builder builder,
        final ReportDefinition reportDefinition, final Set<Long> cids) throws InterruptedException {

    AdWordsSessionBuilderSynchronizer sessionBuilder = new AdWordsSessionBuilderSynchronizer(builder);

    final Collection<Long> failed = new ConcurrentSkipListSet<Long>();
    final Collection<File> results = new ConcurrentSkipListSet<File>();

    // We use a Latch so the main thread knows when all the worker threads are complete.
    final CountDownLatch latch = new CountDownLatch(cids.size());

    Stopwatch stopwatch = Stopwatch.createStarted();

    for (final Long cid : cids) {
        RunnableDownloader downloader = new RunnableDownloader(this.retriesCount, this.backoffInterval,
                this.bufferSize, cid, reportDefinition, sessionBuilder, results);
        downloader.setFailed(failed);
        executeRunnableDownloader(downloader, latch);
    }

    latch.await();
    stopwatch.stop();
    return this.printResultsAndReturn(results, stopwatch.elapsed(TimeUnit.MILLISECONDS), failed, cids);
}

From source file:fr.ens.transcriptome.aozan.RunDataGenerator.java

/**
 * Collect data and return a RunData object.
 * @return a RunData object with all data about the run
 * @throws AozanException if an error occurs while collecting data
 *//*  w w  w  .  ja v  a2s.  c o  m*/
public RunData collect() throws AozanException {

    final RunData data = new RunData();

    if (this.properties.containsKey(COLLECT_DONE)) {
        throw new AozanException("Collect has been already done.");
    }

    if (!this.properties.containsKey(QC.RTA_OUTPUT_DIR)) {
        throw new AozanException("RTA output directory is not set.");
    }

    if (!this.properties.containsKey(QC.CASAVA_DESIGN_PATH)) {
        throw new AozanException("Casava design file path is not set.");
    }

    if (!this.properties.containsKey(QC.CASAVA_OUTPUT_DIR)) {
        throw new AozanException("Casava output directory is not set.");
    }

    if (!this.properties.containsKey(QC.QC_OUTPUT_DIR)) {
        throw new AozanException("QC output directory is not set.");
    }

    if (!this.properties.containsKey(QC.TMP_DIR)) {
        throw new AozanException("Temporary directory is not set.");
    }

    // Timer
    final Stopwatch timerGlobal = Stopwatch.createStarted();

    LOGGER.info("Step collector start");

    // For all collectors
    for (final Collector collector : this.collectors) {

        final Stopwatch timerCollector = Stopwatch.createStarted();
        LOGGER.info(collector.getName().toUpperCase() + " start");

        // Configure
        collector.configure(new Properties(this.properties));

        // And collect data
        collector.collect(data);

        LOGGER.info(collector.getName().toUpperCase() + " end in "
                + toTimeHumanReadable(timerCollector.elapsed(TimeUnit.MILLISECONDS)));

    }

    for (final Collector collector : this.collectors) {
        collector.clear();
    }

    LOGGER.info("Step collector end in " + toTimeHumanReadable(timerGlobal.elapsed(TimeUnit.MILLISECONDS)));
    timerGlobal.stop();

    this.properties.setProperty(COLLECT_DONE, "true");

    return data;
}

From source file:com.palantir.atlasdb.sweep.BackgroundSweeperImpl.java

private void saveSweepResults(final SweepProgressRowResult progress, final SweepResults results) {
    final long cellsDeleted = fromNullable(progress.getCellsDeleted()) + results.getCellsDeleted();
    final long cellsExamined = fromNullable(progress.getCellsExamined()) + results.getCellsExamined();
    if (results.getNextStartRow().isPresent()) {
        saveIntermediateSweepResults(progress, results.getNextStartRow().get(), cellsDeleted, cellsExamined);
        return;/*ww  w.  j a  v  a 2 s  .com*/
    }

    saveFinalSweepResults(progress, cellsDeleted, cellsExamined);

    log.debug("Finished sweeping {}, examined {} unique cells, deleted {} cells.", progress.getFullTableName(),
            cellsExamined, cellsDeleted);

    if (cellsDeleted > 0) {
        Stopwatch watch = Stopwatch.createStarted();
        kvs.compactInternally(progress.getFullTableName());
        log.debug("Finished performing compactInternally on {} in {} ms.", progress.getFullTableName(),
                watch.elapsed(TimeUnit.MILLISECONDS));
    }

    // Truncate instead of delete because the progress table contains only
    // a single row that has accumulated many overwrites.
    kvs.truncateTable(tableFactory.getSweepProgressTable(null).getTableName());
}

From source file:com.palantir.atlasdb.sweep.BackgroundSweeper.java

private boolean runOnce(Transaction t) {
    SweepProgressTable progressTable = tableFactory.getSweepProgressTable(t);
    Optional<SweepProgressRowResult> optProgress = progressTable.getRow(SweepProgressRow.of(0));
    if (!optProgress.isPresent()) {
        optProgress = chooseNextTableToSweep(t);
    }/*  www.j ava  2  s .c  o  m*/
    if (!optProgress.isPresent()) {
        log.debug("Skipping sweep because no table has enough new writes to be worth sweeping at the moment.");
        return false;
    }
    SweepProgressRowResult progress = optProgress.get();
    Stopwatch watch = Stopwatch.createStarted();
    SweepResults results = sweepRunner.run(progress.getFullTableName(), progress.getStartRow());
    log.debug("Swept {} unique cells from {} and performed {} deletions in {} ms.", results.getCellsExamined(),
            progress.getFullTableName(), results.getCellsDeleted(), watch.elapsed(TimeUnit.MILLISECONDS));
    saveSweepResults(t, progress, results);
    return true;
}

From source file:com.example.appengine.spanner.SpannerTasks.java

static void runTask(Task task, PrintWriter pw) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    switch (task) {
    case createDatabase:
        createDatabase(pw);//from www .ja  v a  2 s  .c o  m
        break;
    case writeExampleData:
        writeExampleData(pw);
        break;
    case query:
        query(pw);
        break;
    case read:
        read(pw);
        break;
    case addMarketingBudget:
        addMarketingBudgetColumnToAlbums(pw);
        break;
    case updateMarketingBudget:
        updateMarketingBudgetData();
        break;
    case queryMarketingBudget:
        queryMarketingBudget(pw);
        break;
    case addIndex:
        addIndex();
        break;
    case readUsingIndex:
        readUsingIndex(pw);
        break;
    case queryUsingIndex:
        queryUsingIndex(pw);
        break;
    case addStoringIndex:
        addStoringIndex();
        break;
    case readStoringIndex:
        readStoringIndex(pw);
        break;
    case readOnlyTransaction:
        readOnlyTransaction(pw);
        break;
    case writeTransaction:
        writeWithTransaction();
        break;
    default:
        break;
    }
    stopwatch.stop();
    pw.println(task + " in milliseconds : " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
    pw.println("====================================================================");
}