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:de.seekircher.techsummit.client.Main.java

public static void main(String[] args) {
    DemoClient client = new DemoClient();
    Stopwatch stopwatch = new Stopwatch();

    for (int i = 0; i < NUM_ITERATIONS; i++) {
        stopwatch.reset().start();
        String response = client.echo("Norbert", DELAY_TIME_SECS, true);

        System.out.println(String.format("Response after %d msecs: %s",
                stopwatch.stop().elapsed(TimeUnit.MILLISECONDS), response));
    }/*from   w  w  w .  j  av  a  2  s .  c o  m*/
}

From source file:eu.thebluemountain.customers.dctm.brownbag.badcontentslister.Main.java

public static void main(String[] args) {
    try {//  ww  w  . j a v  a  2s . c om
        Map<Command, Optional<String>> cmds = Command.parse(args);
        if ((cmds.containsKey(Command.HELP)) || (!cmds.containsKey(Command.CONFIG))) {
            usage();
            return;
        }
        final JDBCConfig config = config(cmds.get(Command.CONFIG).get());

        String pwd = config.password.orNull();
        if (null == pwd) {
            Optional<String> opt = passwordOf("database", config.user);
            if (!opt.isPresent()) {
                throw new ExitException(RetCode.ERR_CANCELLED);
            }
            pwd = opt.get();
        }
        try (JDBCConnection from = create(config, pwd); CSVWriter writer = makeLog(config.user)) {
            Stopwatch watch = Stopwatch.createStarted();
            Stores stores = StoresReader.STORESREADER.apply(from);
            System.out.println("spent " + watch.stop() + " to load stores");
            final Function<DecoratedContent, Checks.Result> checker = Checks.checker(stores);
            final Multiset<Checks.Code> codes = TreeMultiset.create();
            watch.reset().start();
            ResponseUI rui = ResponseUI.create(1024, 64);
            try (CloseableIterator<DecoratedContent> it = DCReader.reader(from, stores)) {
                long count = 0L;
                while (it.hasNext()) {
                    DecoratedContent dc = it.next();
                    count++;
                    final Checks.Result result = checker.apply(dc);
                    assert null != result;
                    rui.onResponse(result);
                    final Checks.Code code = result.code;
                    codes.add(code);
                    if (code != Checks.Code.OK) {
                        // we've got an error then ....
                        writer.writeError(dc, result);
                    }
                }
                rui.finish();
                System.out.println("spent " + watch.stop() + " to read " + count + " d.c.");
                System.out.println("stats: " + codes);
                System.out.println("bye");
            }
        }
    } catch (SQLException e) {
        e.printStackTrace(System.err);
        System.err.flush();
        System.out.println();
        usage();
        System.exit(RetCode.ERR_SQL.ordinal());
    } catch (ExitException e) {
        e.exit();
    } catch (RuntimeException | IOException e) {
        e.printStackTrace(System.err);
        System.err.flush();
        System.out.println();
        usage();
        System.exit(RetCode.ERR_OTHER.ordinal());
    }
}

From source file:org.cinchapi.concourse.shell.ConcourseShell.java

/**
 * Run the program...//w  w w  .  j  a  v a  2 s.  co  m
 * 
 * @param args - see {@link Options}
 * @throws IOException
 */
public static void main(String... args) throws IOException {
    ConsoleReader console = new ConsoleReader();
    console.setExpandEvents(false);
    Options opts = new Options();
    JCommander parser = new JCommander(opts, args);
    parser.setProgramName("concourse-shell");
    if (opts.help) {
        parser.usage();
        System.exit(1);
    }
    if (Strings.isNullOrEmpty(opts.password)) {
        opts.password = console.readLine("Password [" + opts.username + "]: ", '*');
    }
    try {
        Concourse concourse = Concourse.connect(opts.host, opts.port, opts.username, opts.password,
                opts.environment);

        final String env = concourse.getServerEnvironment();

        CommandLine.displayWelcomeBanner();
        Binding binding = new Binding();
        GroovyShell shell = new GroovyShell(binding);

        Stopwatch watch = Stopwatch.createUnstarted();
        console.println("Client Version " + Version.getVersion(ConcourseShell.class));
        console.println("Server Version " + concourse.getServerVersion());
        console.println("");
        console.println("Connected to the '" + env + "' environment.");
        console.println("");
        console.println("Type HELP for help.");
        console.println("Type EXIT to quit.");
        console.println("Use TAB for completion.");
        console.println("");
        console.setPrompt(MessageFormat.format("[{0}/cash]$ ", env));
        console.addCompleter(new StringsCompleter(getAccessibleApiMethodsUsingShortSyntax()));

        final List<String> methods = Lists.newArrayList(getAccessibleApiMethods());
        String line;
        while ((line = console.readLine().trim()) != null) {
            line = SyntaxTools.handleShortSyntax(line, methods);
            binding.setVariable("concourse", concourse);
            binding.setVariable("eq", Operator.EQUALS);
            binding.setVariable("ne", Operator.NOT_EQUALS);
            binding.setVariable("gt", Operator.GREATER_THAN);
            binding.setVariable("gte", Operator.GREATER_THAN_OR_EQUALS);
            binding.setVariable("lt", Operator.LESS_THAN);
            binding.setVariable("lte", Operator.LESS_THAN_OR_EQUALS);
            binding.setVariable("bw", Operator.BETWEEN);
            binding.setVariable("regex", Operator.REGEX);
            binding.setVariable("nregex", Operator.NOT_REGEX);
            binding.setVariable("lnk2", Operator.LINKS_TO);
            binding.setVariable("date", STRING_TO_TIME);
            binding.setVariable("time", STRING_TO_TIME);
            binding.setVariable("where", WHERE);
            binding.setVariable("tag", STRING_TO_TAG);
            if (line.equalsIgnoreCase("exit")) {
                concourse.exit();
                System.exit(0);
            } else if (line.equalsIgnoreCase("help") || line.equalsIgnoreCase("man")) {
                Process p = Runtime.getRuntime()
                        .exec(new String[] { "sh", "-c", "echo \"" + HELP_TEXT + "\" | less > /dev/tty" });
                p.waitFor();
            } else if (containsBannedCharSequence(line)) {
                System.err.println(
                        "Cannot complete command because " + "it contains an illegal character sequence.");
            } else if (Strings.isNullOrEmpty(line)) { // CON-170
                continue;
            } else {
                watch.reset().start();
                Object value = null;
                try {
                    value = shell.evaluate(line, "ConcourseShell");
                    watch.stop();
                    if (value != null) {
                        System.out.println(
                                "Returned '" + value + "' in " + watch.elapsed(TimeUnit.MILLISECONDS) + " ms");
                    } else {
                        System.out.println("Completed in " + watch.elapsed(TimeUnit.MILLISECONDS) + " ms");
                    }
                } catch (Exception e) {
                    if (e.getCause() instanceof TTransportException) {
                        die(e.getMessage());
                    } else if (e.getCause() instanceof TSecurityException) {
                        die("A security change has occurred and your " + "session cannot continue");
                    } else {
                        System.err.print("ERROR: " + e.getMessage());
                    }
                }

            }
            System.out.print("\n");
        }
    } catch (Exception e) {
        if (e.getCause() instanceof TTransportException) {
            die("Unable to connect to " + opts.username + "@" + opts.host + ":" + opts.port
                    + " with the specified password");
        } else if (e.getCause() instanceof TSecurityException) {
            die("Invalid username/password combination.");
        } else {
            die(e.getMessage());
        }
    } finally {
        try {
            TerminalFactory.get().restore();
        } catch (Exception e) {
            die(e.getMessage());
        }
    }

}

From source file:ezbake.data.common.LoggingUtils.java

public static void logResetAndStartStopWatch(Logger logger, Stopwatch watch, String name) {
    watch.stop();// w  ww . ja v  a 2  s.  c o  m
    logger.info("{}|{} miliseconds", name, watch.elapsed(TimeUnit.MILLISECONDS));
    watch.reset();
    watch.start();
}

From source file:processing.MPCalculator.java

private static List<int[]> getPopularTags(BookmarkReader reader, int sampleSize, int limit) {
    List<int[]> tags = new ArrayList<int[]>();
    Stopwatch timer = new Stopwatch();
    timer.start();//from   w  ww  .ja v a  2 s  .com

    int[] tagIDs = getPopularTagList(reader, limit);

    timer.stop();
    long trainingTime = timer.elapsed(TimeUnit.MILLISECONDS);
    timer.reset();
    timer.start();
    for (int j = 0; j < sampleSize; j++) {
        tags.add(tagIDs);
    }
    timer.stop();
    long testTime = timer.elapsed(TimeUnit.MILLISECONDS);

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

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

public static void logTime(String section, Stopwatch stopwatch) {
    if (System.getProperty("android.newShrinker.profile") != null) {
        System.out.println(section + ": " + stopwatch);
        stopwatch.reset();
        stopwatch.start();//from  ww w  .j  a  v  a  2s.  com
    }
}

From source file:processing.MPurCalculator.java

public static List<Map<Integer, Double>> startLanguageModelCreation(BookmarkReader reader, int sampleSize,
        boolean sorting, boolean userBased, boolean resBased, int beta) {
    int size = reader.getBookmarks().size();
    int trainSize = size - sampleSize;

    Stopwatch timer = new Stopwatch();
    timer.start();/* ww  w.  ja  va2  s  . c  o  m*/
    MPurCalculator calculator = new MPurCalculator(reader, trainSize, beta, userBased, resBased);
    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);
        results.add(map);
    }
    timer.stop();
    long testTime = timer.elapsed(TimeUnit.MILLISECONDS);

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

From source file:itemrecommendations.CFResourceCalculator.java

private static List<Map<Integer, Double>> startBM25CreationForResourcesPrediction(BookmarkReader reader,
        int sampleSize, boolean userBased, boolean resBased, boolean allResources, boolean bll,
        Features features) {//  ww w  .j a v a  2  s  . c o m
    int size = reader.getBookmarks().size();
    int trainSize = size - sampleSize;

    Stopwatch timer = new Stopwatch();
    timer.start();
    CFResourceCalculator calculator = new CFResourceCalculator(reader, trainSize, false, userBased, resBased, 5,
            Similarity.COSINE, features);
    timer.stop();
    long trainingTime = timer.elapsed(TimeUnit.MILLISECONDS);

    timer.reset();
    timer.start();
    List<Map<Integer, Double>> results = new ArrayList<Map<Integer, Double>>();
    for (Integer userID : reader.getUniqueUserListFromTestSet(trainSize)) {
        Map<Integer, Double> map = null;
        map = calculator.getRankedResourcesList(userID, -1, true, allResources, bll, true, false); // TODO
        results.add(map);
    }
    timer.stop();
    long testTime = timer.elapsed(TimeUnit.MILLISECONDS);

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

From source file:com.codereligion.cherry.benchmark.BenchmarkRunner.java

public static Func1<Input, Observable<Output>> benchMark() {
    return new Func1<Input, Observable<Output>>() {
        @Override/*from  w w  w . ja  va  2 s  .  co  m*/
        public Observable<Output> call(final Input input) {
            final Output output = Output.from(input);

            output.withGuavaContestant(benchMark(input.getRepetitions(), input.getGuavaResult()));
            output.withCherryContestant(benchMark(input.getRepetitions(), input.getCherryResult()));

            return Observable.just(output);
        }

        private ContestantResult benchMark(final long repetitions, final Contestant contestant) {

            int checkInt = 0;
            final Stopwatch stopwatch = Stopwatch.createUnstarted();
            final ContestantResult contestantResult = ContestantResult.from(contestant);

            for (long reps = 0; reps < repetitions; reps++) {

                System.gc();
                stopwatch.start();
                checkInt |= contestant.run();
                stopwatch.stop();

                final long timeInNanos = stopwatch.elapsed(TimeUnit.NANOSECONDS);
                contestantResult.addRunTime(timeInNanos);
                stopwatch.reset();
            }

            System.out.println("check int:" + checkInt);

            return contestantResult;
        }
    };
}

From source file:com.google.devtools.build.android.AndroidResourceMerger.java

/** Merges all secondary resources with the primary resources. */
public static MergedAndroidData mergeData(final ParsedAndroidData primary, final Path primaryManifest,
        final List<? extends SerializedAndroidData> direct,
        final List<? extends SerializedAndroidData> transitive, final Path resourcesOut, final Path assetsOut,
        @Nullable final PngCruncher cruncher, final VariantType type, @Nullable final Path symbolsOut,
        @Nullable AndroidResourceClassWriter rclassWriter, AndroidDataDeserializer deserializer)
        throws MergingException {
    Stopwatch timer = Stopwatch.createStarted();
    final ListeningExecutorService executorService = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(15));
    try (Closeable closeable = ExecutorServiceCloser.createWith(executorService)) {
        AndroidDataMerger merger = AndroidDataMerger.createWithPathDeduplictor(executorService, deserializer);
        UnwrittenMergedAndroidData merged = mergeData(executorService, transitive, direct, primary,
                primaryManifest, type != VariantType.LIBRARY, deserializer);
        timer.reset().start();
        if (symbolsOut != null) {
            AndroidDataSerializer serializer = AndroidDataSerializer.create();
            merged.serializeTo(serializer);
            serializer.flushTo(symbolsOut);
            logger.fine(/*from  w  w  w. j av a 2s. c om*/
                    String.format("serialize merge finished in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
            timer.reset().start();
        }
        if (rclassWriter != null) {
            merged.writeResourceClass(rclassWriter);
            logger.fine(String.format("write classes finished in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
            timer.reset().start();
        }
        AndroidDataWriter writer = AndroidDataWriter.createWith(resourcesOut.getParent(), resourcesOut,
                assetsOut, cruncher, executorService);
        return merged.write(writer);
    } catch (IOException e) {
        throw MergingException.wrapException(e).build();
    } finally {
        logger.fine(String.format("write merge finished in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
    }
}