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

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

Introduction

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

Prototype

@CheckReturnValue
public static Stopwatch createUnstarted() 

Source Link

Document

Creates (but does not start) a new stopwatch using System#nanoTime as its time source.

Usage

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

/**
 * Run the program...//w ww. j a v  a2  s.  c om
 * 
 * @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:jobs.ComputeOpenIF.java

@Override
public void doJob() throws Exception {

    Logger.info("Job open IF started...");
    Stopwatch stopwatch = Stopwatch.createUnstarted();
    stopwatch.start();/*from  w ww  .j  a  v  a2 s. co  m*/

    //IF(2013) = articles published in 2011 and 2012
    //A = # of times articles published in journal in 2011 and 2012 are cited - ideally calculated in very beginning 2014, when all citations that happened
    //in 2013 have been considered.
    //B = # of articles published by the journal in 2011 and 2012.
    //IF(2013) = A/B
    int now = Integer.parseInt((String) play.Play.configuration.get("analysis.year"));
    int y2 = now - 2;

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date start = sdf.parse("01/01/" + now);
    Date end = sdf.parse("31/12/" + y2);

    Logger.info("Getting citations...");
    List<Citation> citations = Citation.find("created between ? and ?", end, start).fetch();

    int counter = 0;
    int total = citations.size();

    //Map holding the journal's journalAbbreviation and their citation counts.
    HashMap<String, List<Integer>> citationMap = new HashMap<String, List<Integer>>();

    for (Citation citation : citations) {
        counter++;
        Logger.info(counter + "/" + total);
        if (citationMap.containsKey(citation.journalAbbreviation)) {
            List<Integer> citationCounts = citationMap.get(citation.journalAbbreviation);
            citationCounts.add(citation.citationCount);
        } else {
            List<Integer> citationCounts = new ArrayList<Integer>();
            citationCounts.add(citation.citationCount);
            citationMap.put(citation.journalAbbreviation, citationCounts);
        }
        Logger.info(citation.journalAbbreviation + ": " + citationMap.get(citation.journalAbbreviation));
    }

    //Save the jazz

    //            double openIF = 0.0;
    //            double deviationIF = 0.0;
    //Compute the IF = mean citations per article published in the two previous years.
    //            if (citations.size() > 0) {
    //                openIF = (double) sum(citationCounts) / citations.size();
    //            }
    //            Logger.info("- IF: " + openIF);
    //Compute the standard deviation of the sample (population)
    //            double squaredDiff = 0.0;
    //            for (Integer citationCount : citationCounts) {
    //                double diff = Math.pow(citationCount - openIF, 2);
    //                squaredDiff += diff;
    //            }
    //
    //            if (citations.size() > 0) {
    //                deviationIF = Math.sqrt(squaredDiff / citations.size());
    //            }
    //            Logger.info("- Deviation: " + deviationIF);
    //Save the modifications
    //            journal.openImpactFactor = openIF;
    //            journal.deviationIF = deviationIF;
    //            journal.save();
    stopwatch.stop();
    Utils.emailAdmin("Stratified index built",
            "Job finished in " + stopwatch.elapsed(TimeUnit.MINUTES) + " minutes.");
}

From source file:com.topekalabs.threads.ThreadUtils.java

public static <T> void done(Collection<Future<T>> futures, long timeout, TimeUnit timeUnit)
        throws TimeoutException, InterruptedException, ExecutionException {
    long milliTimeout = MILLIS_UNIT.convert(timeout, timeUnit);
    long currentTimeout = milliTimeout;

    Stopwatch sw = Stopwatch.createUnstarted();

    for (Future<?> future : futures) {
        sw.start();/*  w w w . j ava2 s . c  o  m*/
        future.get(currentTimeout, MILLIS_UNIT);
        sw.stop();

        long elapsed = sw.elapsed(MILLIS_UNIT);

        if (elapsed > milliTimeout) {
            throw new TimeoutException("Exceeded timeout of " + milliTimeout + " milliseconds.");
        }

        currentTimeout = milliTimeout - elapsed;
    }
}

From source file:jobs.LuceneIndexingInDb.java

@Override
public void doJob() throws Exception {

    Logger.info("Saving index in DB...");
    Stopwatch stopwatch = Stopwatch.createUnstarted();
    stopwatch.start();/*from  w w  w  .  j  a va 2s . c  om*/

    //TODO do not hardcode year value
    Directory directory = FSDirectory.open(VirtualFile.fromRelativePath("/indexes/index-2013").getRealFile());

    DirectoryReader ireader = DirectoryReader.open(directory);
    //Returns an error is the field does not exists
    //Do the same for abstract (first if possible)
    Terms terms = SlowCompositeReaderWrapper.wrap(ireader).terms("contents");
    TermsEnum iterator = terms.iterator(null);
    BytesRef byteRef;

    int counter = 0;

    while ((byteRef = iterator.next()) != null) {
        String term = new String(byteRef.bytes, byteRef.offset, byteRef.length);

        //Could be used later
        int frequency = iterator.docFreq();
        //Save to DB
        //check if exists alread, if yes increase the counter, otherwise create
        //Saves only the terms with high frequency
        //Removes the terms with a _ (from shigle index) and 4 decimals (dates)

        if (frequency > FREQ_TRESHOLD && !term.contains("_")) {
            new Phrase(term, frequency).save();
            Logger.info("Term: " + term + " - freq: " + frequency);
        }

        if (counter % 1000 == 0) {
            Phrase.em().flush();
            Phrase.em().clear();
        }

    }
    stopwatch.stop();
    Utils.emailAdmin("Indexing in DB done. ",
            "Job finished in " + stopwatch.elapsed(TimeUnit.MINUTES) + " minutes.");

    Logger.info("index done and saved.");
}

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.  jav  a 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:org.graylog.plugins.pipelineprocessor.simulator.PipelineInterpreterTracer.java

public PipelineInterpreterTracer() {
    executionTrace = new ArrayList<>();
    timer = Stopwatch.createUnstarted();
    simulatorInterpreterListener = new SimulatorInterpreterListener(this);
}

From source file:jobs.ComputeNCITdistribution.java

@Override
public void doJob() throws Exception {

    Logger.info("Job started...");
    Stopwatch stopwatch = Stopwatch.createUnstarted();
    stopwatch.start();/*from  w  w  w  .  j a v  a 2  s  .  c o  m*/

    List<MorphiaOntologyTerm> terms = MorphiaOntologyTerm.findAll();

    int total = terms.size();
    int counter = 0;
    Directory directory = FSDirectory.open(VirtualFile.fromRelativePath("/indexes/index-2013").getRealFile());
    DirectoryReader ireader = DirectoryReader.open(directory);

    //Just chunck the words - no stop word removal - such concept will not give any result in principle
    Analyzer analyzer = new CustomStopWordsStandardAnalyzer(Version.LUCENE_47);
    IndexSearcher isearcher = new IndexSearcher(ireader);
    QueryParser parser = new QueryParser(Version.LUCENE_47, "contents", analyzer);

    for (MorphiaOntologyTerm ontologyTerm : terms) {
        counter++;

        Logger.info("i: " + counter + "/" + total);
        Stopwatch timeQuery = Stopwatch.createUnstarted();
        timeQuery.start();
        Query query = parser.parse("\"" + ontologyTerm.value + "\"");
        ScoreDoc[] hits = isearcher.search(query, null, 100000000).scoreDocs;
        timeQuery.stop();
        Logger.info("Query time: " + timeQuery.elapsed(TimeUnit.MILLISECONDS));

        Stopwatch timeUpdate = Stopwatch.createUnstarted();
        timeUpdate.start();
        ontologyTerm.frequency = hits.length;
        ontologyTerm.save();
        timeUpdate.stop();
        Logger.info("Update time: " + timeUpdate.elapsed(TimeUnit.MILLISECONDS));
        Logger.info("Query: " + ontologyTerm.value + " - " + hits.length);
    }

    stopwatch.stop();
    Utils.emailAdmin("Distribution completed",
            "Job finished in " + stopwatch.elapsed(TimeUnit.MINUTES) + " minutes.");
    Logger.info("Job finished");

}

From source file:io.druid.segment.LoggingProgressIndicator.java

public LoggingProgressIndicator(String progressName) {
    this.progressName = progressName;
    this.global = Stopwatch.createUnstarted();
}

From source file:edu.wpi.first.wpilibj.UnitTestUtility.java

/**
 * Sets up the base system WPILib so that it does not rely on hardware.
 */// w  ww . j av a  2s . co m
public static void setupMockBase() {
    try {
        // Check to see if this has been setup
        Timer.getFPGATimestamp();
    } catch (BaseSystemNotInitializedException ex) {
        // If it hasn't been then do this setup

        HLUsageReporting.SetImplementation(new HLUsageReporting.Null());
        RobotState.SetImplementation(new MockRobotStateInterface());
        Timer.SetImplementation(new Timer.StaticInterface() {

            @Override
            public double getFPGATimestamp() {
                return System.currentTimeMillis() / 1000.0;
            }

            @Override
            public double getMatchTime() {
                return 0;
            }

            @Override
            public void delay(double seconds) {
                try {
                    Thread.sleep((long) (seconds * 1e3));
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException("Thread was interrupted", ex);
                }
            }

            @Override
            public Timer.Interface newTimer() {
                return new Timer.Interface() {
                    private final Stopwatch m_stopwatch = Stopwatch.createUnstarted();

                    @Override
                    public double get() {
                        return m_stopwatch.elapsed(TimeUnit.SECONDS);
                    }

                    @Override
                    public void reset() {
                        m_stopwatch.reset();
                    }

                    @Override
                    public void start() {
                        m_stopwatch.start();
                    }

                    @Override
                    public void stop() {
                        m_stopwatch.stop();
                    }

                    @Override
                    public boolean hasPeriodPassed(double period) {
                        if (get() > period) {
                            // Advance the start time by the period.
                            // Don't set it to the current time... we want to avoid drift.
                            m_stopwatch.reset().start();
                            return true;
                        }
                        return false;
                    }
                };
            }
        });
    }
}

From source file:com.github.benmanes.caffeine.cache.simulator.policy.PolicyStats.java

public PolicyStats(String name) {
    this.name = requireNonNull(name);
    this.stopwatch = Stopwatch.createUnstarted();
}