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

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

Introduction

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

Prototype

public Stopwatch reset() 

Source Link

Document

Sets the elapsed time for this stopwatch to zero, and places it in a stopped state.

Usage

From source file:io.prestosql.verifier.VerifyCommand.java

@VisibleForTesting
static List<QueryPair> rewriteQueries(SqlParser parser, VerifierConfig config, List<QueryPair> queries) {
    QueryRewriter testRewriter = new QueryRewriter(parser, config.getTestGateway(),
            config.getShadowTestTablePrefix(), Optional.ofNullable(config.getTestCatalogOverride()),
            Optional.ofNullable(config.getTestSchemaOverride()),
            Optional.ofNullable(config.getTestUsernameOverride()),
            Optional.ofNullable(config.getTestPasswordOverride()), config.getDoublePrecision(),
            config.getTestTimeout());/*from w ww  . j av  a  2 s .  c o  m*/

    QueryRewriter controlRewriter = new QueryRewriter(parser, config.getControlGateway(),
            config.getShadowControlTablePrefix(), Optional.ofNullable(config.getControlCatalogOverride()),
            Optional.ofNullable(config.getControlSchemaOverride()),
            Optional.ofNullable(config.getControlUsernameOverride()),
            Optional.ofNullable(config.getControlPasswordOverride()), config.getDoublePrecision(),
            config.getControlTimeout());

    LOG.info("Rewriting %s queries using %s threads", queries.size(), config.getThreadCount());
    ExecutorService executor = newFixedThreadPool(config.getThreadCount());
    CompletionService<Optional<QueryPair>> completionService = new ExecutorCompletionService<>(executor);

    List<QueryPair> rewritten = new ArrayList<>();
    for (QueryPair pair : queries) {
        completionService.submit(() -> {
            try {
                return Optional.of(
                        new QueryPair(pair.getSuite(), pair.getName(), testRewriter.shadowQuery(pair.getTest()),
                                controlRewriter.shadowQuery(pair.getControl())));
            } catch (QueryRewriteException | SQLException e) {
                if (!config.isQuiet()) {
                    LOG.warn(e, "Failed to rewrite %s for shadowing. Skipping.", pair.getName());
                }
                return Optional.empty();
            }
        });
    }

    executor.shutdown();

    try {
        Stopwatch stopwatch = Stopwatch.createStarted();
        for (int n = 1; n <= queries.size(); n++) {
            completionService.take().get().ifPresent(rewritten::add);

            if (!config.isQuiet() && (stopwatch.elapsed(MINUTES) > 0)) {
                stopwatch.reset().start();
                LOG.info("Rewrite progress: %s valid, %s skipped, %.2f%% done", rewritten.size(),
                        n - rewritten.size(), (((double) n) / queries.size()) * 100);
            }
        }
    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException("Query rewriting failed", e);
    }

    LOG.info("Rewrote %s queries into %s queries", queries.size(), rewritten.size());
    return rewritten;
}

From source file:processing.BLLCalculator.java

private static List<Map<Integer, Double>> startActCreation(BookmarkReader reader, int sampleSize,
        boolean sorting, boolean userBased, boolean resBased, double dVal, int beta, CalculationType cType,
        Double lambda) {/*from w  w w  . j a  va 2  s . com*/
    int size = reader.getBookmarks().size();
    int trainSize = size - sampleSize;

    Stopwatch timer = new Stopwatch();
    timer.start();
    BLLCalculator calculator = new BLLCalculator(reader, trainSize, dVal, beta, userBased, resBased, cType,
            lambda);
    timer.stop();
    long trainingTime = timer.elapsed(TimeUnit.MILLISECONDS);
    List<Map<Integer, Double>> results = new ArrayList<Map<Integer, Double>>();
    if (trainSize == size) {
        trainSize = 0;
    }

    timer.reset();
    timer.start();
    for (int i = trainSize; i < size; i++) { // the test-set
        Bookmark data = reader.getBookmarks().get(i);
        Map<Integer, Double> map = calculator.getRankedTagList(data.getUserID(), data.getResourceID(), sorting,
                cType);
        results.add(map);
    }
    timer.stop();
    long testTime = timer.elapsed(TimeUnit.MILLISECONDS);

    timeString = PerformanceMeasurement.addTimeMeasurement(timeString, true, trainingTime, testTime,
            sampleSize);
    return results;
}

From source file:org.apache.kudu.client.DeadlineTracker.java

/**
 * Creates a new tracker, using the specified stopwatch, and starts it right now.
 * The stopwatch is reset if it was already running.
 * @param stopwatch Specific Stopwatch to use
 *///from w  ww .  jav  a2s  .  com
public DeadlineTracker(Stopwatch stopwatch) {
    if (stopwatch.isRunning()) {
        stopwatch.reset();
    }
    this.stopwatch = stopwatch.start();
}

From source file:org.trustedanalytics.uploader.core.listener.FileUploadListener.java

public FileUploadListener(long interval, TimeUnit intervalTimeUnit, Stopwatch stopwatch) {
    this.interval = interval;
    this.intervalTimeUnit = intervalTimeUnit;
    this.lastSnapshotSize = 0;
    this.lastSnapshotTime = 0;
    this.stopwatch = stopwatch.reset().start();
    this.filename = new AtomicReference<>();
}

From source file:com.davidbracewell.ml.sequence.indexers.DoublePassIndexer.java

@Override
public List<List<Instance>> index(List<Sequence<V>> data) {
    Resource tempFile = Resources.temporaryFile();
    tempFile.deleteOnExit();/* www . j a  v a2s .  co  m*/
    Set<String> keep = Sets.newHashSet();
    log.info("Beginning indexing...");
    Stopwatch sw = Stopwatch.createStarted();
    count(data, keep, tempFile);
    sw.stop();
    log.info("Finished indexing in {0}", sw);
    log.info("Beginning construction of instances...");
    sw.reset();
    sw.start();
    List<List<Instance>> instances = build(keep, tempFile, data.iterator().next().getFeatures());
    extractors.setFeatures(instances.get(0).get(0).getFeatures());
    extractors.getFeatures().freeze();
    sw.stop();
    log.info("Finished construction of instances in {0}", sw);
    return instances;
}

From source file:pro.foundev.strategies.BenchmarkStrategy.java

private void exec(Runnable runnable, String name, int runs, BenchmarkReport report) {
    logger.info("Starting run of " + name);
    DescriptiveStatistics stats = new DescriptiveStatistics();

    Stopwatch timer = new Stopwatch();
    for (int i = 0; i < runs; i++) {
        timer.start();/*from   w ww .  j  a  v  a2  s.c om*/
        runnable.run();
        timer.stop();
        logger.info("Time to execute load run #" + i + " it took " + timer);
        stats.addValue(timer.elapsed(TimeUnit.MILLISECONDS));
        timer.reset();
    }
    logger.info("Finished run of " + name);
    report.addLine(name, stats.getMin(), stats.getMax(), stats.getPercentile(50), stats.getPercentile(90),
            stats.getMean());
}

From source file:com.facebook.buck.cli.DistBuildLogsCommand.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("Successfully downloaded build information in [%d millis].",
                stopwatch.elapsed(TimeUnit.MILLISECONDS)));

        stopwatch.reset().start();
        List<BuildSlaveRunId> buildSlaves = buildJob.getBuildSlaves().stream().map(x -> x.getBuildSlaveRunId())
                .collect(Collectors.toList());
        stdout.println(String.format("Materializing logs for [%d] BuildSlaves. (%s)", buildSlaves.size(),
                Joiner.on(", ").join(buildSlaves)));
        Path logDir = params.getInvocationInfo().get().getLogDirectoryPath();
        ProjectFilesystem filesystem = params.getCell().getFilesystem();
        BuildSlaveLogsMaterializer materializer = new BuildSlaveLogsMaterializer(service, filesystem, logDir);
        List<BuildSlaveRunId> notMaterialized = materializer
                .fetchAndMaterializeAvailableLogs(buildJob.getStampedeId(), buildSlaves);

        if (notMaterialized.isEmpty()) {
            console.printSuccess(String.format("Successfully materialized all logs into [%s] in [%d millis].",
                    logDir.toAbsolutePath().toString(), stopwatch.elapsed(TimeUnit.MILLISECONDS)));
            return ExitCode.SUCCESS;
        } else if (notMaterialized.size() == buildSlaves.size()) {
            console.printErrorText(String.format("Failed to materialize all logs. Duration=[%d millis].",
                    stopwatch.elapsed(TimeUnit.MILLISECONDS)));
            // TODO: buck(team) proper disambiguate between user errors and fatals
            return ExitCode.BUILD_ERROR;
        } else {//from  w w w  .ja  v a  2 s.co m
            stdout.println(console.getAnsi()
                    .asWarningText(String.format("Materialized [%d] out of [%d] logs into [%s] in [%d millis].",
                            buildSlaves.size() - notMaterialized.size(), buildSlaves.size(),
                            logDir.toAbsolutePath().toString(), stopwatch.elapsed(TimeUnit.MILLISECONDS))));
            return ExitCode.BUILD_ERROR;
        }
    }
}

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();//  w  w  w .jav a2 s. c om
    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: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;//  ww  w .  j a  va  2 s  . 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.geogit.repository.RevTreeBuilder2.java

/**
 * @return the new tree, not saved to the object database. Any bucket tree though is saved when
 *         this method returns./*from w w w. j a  v a  2  s.  co m*/
 */
public RevTree build() {
    if (nodeIndex == null) {
        return original.builder(db).build();
    }

    Stopwatch sw = new Stopwatch().start();
    RevTreeBuilder builder;
    try {
        builder = new RevTreeBuilder(db, original);
        Iterator<Node> nodes = nodeIndex.nodes();
        while (nodes.hasNext()) {
            Node node = nodes.next();
            builder.put(node);
        }
    } finally {
        nodeIndex.close();
    }
    LOGGER.debug("Index traversed in {}", sw.stop());
    sw.reset().start();

    RevTree namedTree = builder.build();
    saveExtraFeatureTypes();
    LOGGER.debug("RevTreeBuilder.build() in {}", sw.stop());
    return namedTree;
}