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

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

Introduction

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

Prototype

Stopwatch() 

Source Link

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();// w  ww .jav a  2 s .  co m
        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 source file:hr.fer.tel.rovkp.homework02.task01.Program.java

public static void main(String[] args) throws Exception {
    Stopwatch timer = new Stopwatch();
    timer.start();//  w w  w . j ava  2s.com

    if (args.length != 2) {
        timer.stop();
        System.err.println("Usage: <jar> <input path> <output path>");
        return;
    }

    Job job = Job.getInstance();
    job.setJarByClass(Program.class);
    job.setJobName("TripTimes");

    FileInputFormat.addInputPath(job, new Path(args[0]));
    FileOutputFormat.setOutputPath(job, new Path(args[1]));

    job.setMapperClass(TripTimesMapper.class);
    // job.setCombinerClass(TripTimesReducer.class);
    job.setReducerClass(TripTimesReducer.class);

    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(TripTimesTuple.class);

    // job.setNumReduceTasks(1);

    job.waitForCompletion(true);
    timer.stop();
    System.out.println("Total time: " + timer.elapsedTime(TimeUnit.SECONDS) + "s");
}

From source file:com.wamad.IRCConnectionExample.java

public static void main(String[] args) throws InterruptedException {
    Stopwatch timer = new Stopwatch().start();
    IRCConnection conn = new IRCConnection("irc.freenode.net", 6667, 6669, null, "Foo-bot", "Mr-Foobar",
            "foo@bar.com");

    final PrintStream out = System.out;

    conn.addIRCEventListener(new IRCEventListener() {
        private Stopwatch stopwatch = new Stopwatch().start();

        public void onRegistered() {
            out.println("Registered");
            out.println("time (" + stopwatch.elapsedMillis());
        }/* w ww . j a va2s . co m*/

        public void onDisconnected() {
            out.println("Disconnected");
            out.println("time (" + stopwatch.elapsedMillis());
        }

        public void onError(final String msg) {
            out.println("Error: " + msg);
            out.println("time (" + stopwatch.elapsedMillis());
        }

        public void onError(final int num, final String msg) {
            out.println("Error: num (" + num + "), msg (" + msg + ")");
            out.println("time (" + stopwatch.elapsedMillis());
        }

        public void onInvite(final String chan, final IRCUser user, final String passiveNick) {
            out.println("invite: chan (" + chan + "), user(" + user + "), pass(" + passiveNick + ")");
            out.println("time (" + stopwatch.elapsedMillis());
        }

        public void onJoin(final String chan, final IRCUser user) {
            out.println("join - " + chan + ", " + user);
            out.println("time (" + stopwatch.elapsedMillis());
        }

        public void onKick(final String chan, final IRCUser user, final String passiveNick, final String msg) {
            out.println("kick - " + chan + ", " + user + ", " + passiveNick + ", " + msg);
            out.println("time (" + stopwatch.elapsedMillis());
        }

        public void onMode(final String chan, final IRCUser user, final IRCModeParser modeParser) {
            out.println("mode - " + chan + ", " + user + ", " + modeParser);
            out.println("time (" + stopwatch.elapsedMillis());
        }

        public void onMode(final IRCUser user, final String passiveNick, final String mode) {
            out.println("mode - " + user + ", " + passiveNick + ", " + mode);
            out.println("time (" + stopwatch.elapsedMillis());
        }

        public void onNick(final IRCUser user, final String newNick) {
            out.println("Nikc - " + user + ", " + newNick);
            out.println("time (" + stopwatch.elapsedMillis());
        }

        public void onNotice(final String target, final IRCUser user, final String msg) {
            out.println("notice - " + target + ", " + user + ", " + msg);
            out.println("time (" + stopwatch.elapsedMillis());
        }

        public void onPart(final String chan, final IRCUser user, final String msg) {
            out.println("part - " + chan + ", " + user + ", " + msg);
            out.println("time (" + stopwatch.elapsedMillis());
        }

        public void onPing(final String ping) {
            out.println("ping - " + ping);
            out.println("time (" + stopwatch.elapsedMillis());
        }

        public void onPrivmsg(final String target, final IRCUser user, final String msg) {
            out.println("privmsg - " + target + ", " + user + ", " + msg);
            out.println("time (" + stopwatch.elapsedMillis());
        }

        public void onQuit(final IRCUser user, final String msg) {
            out.println("quit - " + user + ", " + msg);
            out.println("time (" + stopwatch.elapsedMillis());
        }

        public void onReply(final int num, final String value, final String msg) {
            out.println("reply - " + num + ", " + value + ", " + msg);
            out.println("time (" + stopwatch.elapsedMillis());
        }

        public void onTopic(final String chan, final IRCUser user, final String topic) {
            out.println("topic - " + chan + ", " + user + ", " + topic);
            out.println("time (" + stopwatch.elapsedMillis());
        }

        public void unknown(final String prefix, final String command, final String middle,
                final String trailing) {
            out.println("unknown - " + prefix + ", " + command + ", " + middle + ", " + trailing);
            out.println("time (" + stopwatch.elapsedMillis());
        }
    });
    conn.setDaemon(true);
    conn.setColors(false);
    conn.setPong(true);

    try {
        out.println("Connecting");
        conn.connect();
        out.println("Connected?");

        conn.doJoin("##gibson");

        System.out.println("Time taken: " + timer.elapsedMillis());

        while (true) {
            conn.doPrivmsg("the_minh_net", "YOU ARE THE MINH");
            conn.doPrivmsg("##gibson", "Testing");
            TimeUnit.SECONDS.sleep(5);
        }

        //      conn.run();
    } catch (IOException e) {
        Throwables.propagate(e);
    }
}

From source file:com.github.benmanes.multiway.Profile.java

public static void main(String[] args) throws Exception {
    final MultiwayPool<Integer, Integer> multiway = MultiwayPoolBuilder.newBuilder()
            //.expireAfterAccess(2, TimeUnit.MINUTES)
            .maximumSize(100).build();//from   w w w.ja v  a  2 s  .  co  m
    final Callable<Integer> resourceLoader = new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            return Integer.MAX_VALUE;
        }
    };

    final LongAdder calls = new LongAdder();
    Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(new Runnable() {
        final Stopwatch stopwatch = new Stopwatch().start();

        @Override
        public void run() {
            long count = calls.longValue();
            long rate = count / stopwatch.elapsed(TimeUnit.SECONDS);
            System.out.printf("%s - %,d [%,d / sec]\n", stopwatch, count, rate);
        }
    }, DISPLAY_DELAY_SEC, DISPLAY_DELAY_SEC, TimeUnit.SECONDS);
    ConcurrentTestHarness.timeTasks(25, new Runnable() {
        @Override
        public void run() {
            Integer id = 1;
            for (;;) {
                Integer resource = multiway.borrow(id, resourceLoader, 100, TimeUnit.MICROSECONDS);
                multiway.release(resource, 100, TimeUnit.MICROSECONDS);
                calls.increment();
            }
        }
    });
}

From source file:org.apache.drill.exec.RunRootExec.java

public static void main(String args[]) throws Exception {
    String path = args[0];//from  w  w w.j a v a 2s . c  o  m
    int iterations = Integer.parseInt(args[1]);
    Drillbit bit = new Drillbit(c, RemoteServiceSet.getLocalServiceSet());
    bit.run();
    DrillbitContext bitContext = bit.getContext();
    PhysicalPlanReader reader = bitContext.getPlanReader();
    PhysicalPlan plan = reader.readPhysicalPlan(Files.toString(new File(path), Charsets.UTF_8));
    FunctionImplementationRegistry registry = bitContext.getFunctionImplementationRegistry();
    FragmentContext context = new FragmentContext(bitContext, PlanFragment.getDefaultInstance(), null,
            registry);
    SimpleRootExec exec;
    for (int i = 0; i < iterations; i++) {
        Stopwatch w = new Stopwatch().start();
        System.out.println("STARTITER:" + i);
        exec = new SimpleRootExec(
                ImplCreator.getExec(context, (FragmentRoot) plan.getSortedOperators(false).iterator().next()));

        while (exec.next()) {
            for (ValueVector v : exec) {
                v.clear();
            }
        }
        System.out.println("ENDITER: " + i);
        System.out.println("TIME: " + w.elapsed(TimeUnit.MILLISECONDS) + "ms");
        exec.close();
    }
    context.close();
    bit.close();
}

From source file:com.sri.ai.distributed.experiment.SimpleExperiment.java

public static void main(String[] args) {
    String cnfFileName = args[0];
    DIMACSReader dimacsReader = new SimplifiedDIMACSReader();

    CNFProblem cnfProblem = dimacsReader.read(cnfFileName);

    cnfProblem.getClauses().cache();/*w  ww . j av  a  2  s . c  o m*/

    System.out.println("# variables        = " + cnfProblem.getNumberVariables());
    System.out.println("# clauses reported = " + cnfProblem.getNumberClauses() + ", number clauses loaded = "
            + cnfProblem.getClauses().count());

    Stopwatch sw = new Stopwatch();

    sw.start();
    SATSolver solver = newSolver();
    int[] model = solver.findModel(cnfProblem);
    sw.stop();

    System.out.println("Took " + sw);

    if (model == null) {
        System.out.println("Problem is NOT satisfiable");
    } else {
        StringJoiner sj = new StringJoiner(", ");
        for (int i = 0; i < model.length; i++) {
            sj.add("" + model[i]);
        }

        System.out.println("Problem is satisfiable, example model found:" + sj);
    }
}

From source file:pocman.demo.ClosedCPPDemo.java

public static void main(final String[] args) throws InterruptedException {

    final Stopwatch stopwatch = new Stopwatch();

    final ClosedCPPDemo that = new ClosedCPPDemo(MATCHING_ALGORITHM_1);

    for (final String level : Mazes.LEVELS) {
        final int pocManPosition = level.indexOf(Tile.POCMAN.toCharacter());
        Preconditions.checkState(pocManPosition > -1, "POCMAN POSITION NOT FOUND !");
        final char[] data = level.toCharArray();
        data[pocManPosition] = Tile.COIN.toCharacter();

        final Maze maze = Maze.from(data);

        stopwatch.start();/*from   ww  w .  ja va 2s . c o m*/
        final ClosedCPPSolution<MazeNode> closedCPPSolution = that.solve(maze);
        stopwatch.stop();

        final EulerianTrailInterface<MazeNode> eulerianTrailInterface = maze.get()
                .fetch(EulerianTrailFeature.class).up();
        final List<MazeNode> closedTrail = eulerianTrailInterface.getEulerianTrail(maze.getNode(pocManPosition),
                closedCPPSolution.getTraversalByEdge()); // TODO ! maze.getEulerianTrail(startingMazeNode)

        that.debug(maze, closedTrail, 160);
        System.out.println(closedCPPSolution);
        Thread.sleep(1000);

        /*
        stopwatch.start();
        final OpenCPPSolution<MazeNode> openCPPSolution = that.solve(closedCPPSolution, maze.getNode(pocManPosition));
        stopwatch.stop();
                
        final List<MazeNode> trail = EulerianTrail.from(
            openCPPSolution.getGraph(),
            openCPPSolution.getTraversalByEdge(),
            openCPPSolution.getEndPoint());
                
        that.debug(maze, trail, 160);
        */

        //break;
    }

    /*
    stopwatch.start();
    final OpenCPPSolution<MazeNode> openCPPSolution = that.solve(closedCPPSolution, maze.getNode(pocManPosition));
    stopwatch.stop();
            
    final List<MazeNode> trail = EulerianTrail.from(
        openCPPSolution.getGraph(),
        openCPPSolution.getTraversalByEdge(),
        openCPPSolution.getEndPoint());
            
    that.debug(maze, trail, 320);
    System.out.println(openCPPSolution);
    Thread.sleep(1000);
    */

    //}

    System.out.println(stopwatch.elapsedTime(TimeUnit.MILLISECONDS) + " " + TimeUnit.MILLISECONDS.toString());
}

From source file:com.couchbase.roadrunner.RoadRunner.java

/**
 * Initialize the RoadRunner.//from w  w w .  j a v a  2s .  co m
 *
 * This method is responsible for parsing the passed in command line arguments
 * and also dispatch the bootstrapping of the actual workload runner.
 *
 * @param args Command line arguments to be passed in.
 */
public static void main(final String[] args) {
    CommandLine params = null;
    try {
        params = parseCommandLine(args);
    } catch (ParseException ex) {
        LOGGER.error("Exception while parsing command line!", ex);
        System.exit(-1);
    }

    if (params.hasOption(OPT_HELP)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("roadrunner", getCommandLineOptions());
        System.exit(0);
    }

    GlobalConfig config = GlobalConfig.fromCommandLine(params);
    WorkloadDispatcher dispatcher = new WorkloadDispatcher(config);

    LOGGER.info("Running with Config: " + config.toString());

    try {
        LOGGER.debug("Initializing ClientHandlers.");
        dispatcher.init();
    } catch (Exception ex) {
        LOGGER.error("Error while initializing the ClientHandlers: ", ex);
        System.exit(-1);
    }

    Stopwatch workloadStopwatch = new Stopwatch().start();
    try {
        LOGGER.info("Running Workload.");
        dispatcher.dispatchWorkload();
    } catch (Exception ex) {
        LOGGER.error("Error while running the Workload: ", ex);
        System.exit(-1);
    }
    workloadStopwatch.stop();

    LOGGER.debug("Finished Workload.");

    LOGGER.info("==== RESULTS ====");

    dispatcher.prepareMeasures();

    long totalOps = dispatcher.getTotalOps();
    long measuredOps = dispatcher.getMeasuredOps();

    LOGGER.info("Operations: measured " + measuredOps + "ops out of total " + totalOps + "ops.");

    Map<String, List<Stopwatch>> measures = dispatcher.getMeasures();
    for (Map.Entry<String, List<Stopwatch>> entry : measures.entrySet()) {
        Histogram h = new Histogram(60 * 60 * 1000, 5);
        for (Stopwatch watch : entry.getValue()) {
            h.recordValue(watch.elapsed(TimeUnit.MICROSECONDS));
        }

        LOGGER.info("Percentile (microseconds) for \"" + entry.getKey() + "\" Workload:");
        LOGGER.info("   50%:" + (Math.round(h.getValueAtPercentile(0.5) * 100) / 100) + "   75%:"
                + (Math.round(h.getValueAtPercentile(0.75) * 100) / 100) + "   95%:"
                + (Math.round(h.getValueAtPercentile(0.95) * 100) / 100) + "   99%:"
                + (Math.round(h.getValueAtPercentile(0.99) * 100) / 100));
    }

    LOGGER.info("Elapsed: " + workloadStopwatch.elapsed(TimeUnit.MILLISECONDS) + "ms");

    List<Stopwatch> elapsedThreads = dispatcher.getThreadElapsed();
    long shortestThread = 0;
    long longestThread = 0;
    for (Stopwatch threadWatch : elapsedThreads) {
        long threadMs = threadWatch.elapsed(TimeUnit.MILLISECONDS);
        if (longestThread == 0 || threadMs > longestThread) {
            longestThread = threadMs;
        }
        if (shortestThread == 0 || threadMs < shortestThread) {
            shortestThread = threadMs;
        }
    }

    LOGGER.info("Shortest Thread: " + shortestThread + "ms");
    LOGGER.info("Longest Thread: " + longestThread + "ms");

}

From source file:cosmos.example.BuildingPermitsExample.java

public static void main(String[] args) throws Exception {
    BuildingPermitsExample example = new BuildingPermitsExample();
    new JCommander(example, args);

    File inputFile = new File(example.fileName);

    Preconditions.checkArgument(inputFile.exists() && inputFile.isFile() && inputFile.canRead(),
            "Expected " + example.fileName + " to be a readable file");

    String zookeepers;/*from w ww.j  av a 2 s .c  o  m*/
    String instanceName;
    Connector connector;
    MiniAccumuloCluster mac = null;
    File macDir = null;

    // Use the MiniAccumuloCluster is requested
    if (example.useMiniAccumuloCluster) {
        macDir = Files.createTempDir();
        String password = "password";
        MiniAccumuloConfig config = new MiniAccumuloConfig(macDir, password);
        config.setNumTservers(1);

        mac = new MiniAccumuloCluster(config);
        mac.start();

        zookeepers = mac.getZooKeepers();
        instanceName = mac.getInstanceName();

        ZooKeeperInstance instance = new ZooKeeperInstance(instanceName, zookeepers);
        connector = instance.getConnector("root", new PasswordToken(password));
    } else {
        // Otherwise connect to a running instance
        zookeepers = example.zookeepers;
        instanceName = example.instanceName;

        ZooKeeperInstance instance = new ZooKeeperInstance(instanceName, zookeepers);
        connector = instance.getConnector(example.username, new PasswordToken(example.password));
    }

    // Instantiate an instance of Cosmos
    Cosmos cosmos = new CosmosImpl(zookeepers);

    // Create a definition for the data we want to load
    Store id = Store.create(connector, new Authorizations(), AscendingIndexIdentitySet.create());

    // Register the definition with Cosmos so it can track its progress.
    cosmos.register(id);

    // Load all of the data from our inputFile
    LoadBuildingPermits loader = new LoadBuildingPermits(cosmos, id, inputFile);
    loader.run();

    // Finalize the SortableResult which will prevent future writes to the data set
    cosmos.finalize(id);

    // Flush the ingest traces to the backend so we can see the results;
    id.sendTraces();

    // Get back the Set of Columns that we've ingested.
    Set<Column> schema = Sets.newHashSet(cosmos.columns(id));

    log.debug("\nColumns: " + schema);

    Iterator<Column> iter = schema.iterator();
    while (iter.hasNext()) {
        Column c = iter.next();
        // Remove the internal ID field and columns that begin with CONTRACTOR_
        if (c.equals(LoadBuildingPermits.ID) || c.name().startsWith("CONTRACTOR_")) {
            iter.remove();
        }
    }

    Iterable<Index> indices = Iterables.transform(schema, new Function<Column, Index>() {

        @Override
        public Index apply(Column col) {
            return Index.define(col);
        }

    });

    // Ensure that we have locality groups set as we expect
    log.info("Ensure locality groups are set");
    id.optimizeIndices(indices);

    // Compact down the data for this SortableResult    
    log.info("Issuing compaction for relevant data");
    id.consolidate();

    final int numTopValues = 10;

    // Walk through each column in the result set
    for (Column c : schema) {
        Stopwatch sw = new Stopwatch();
        sw.start();

        // Get the number of times we've seen each value in a given column
        CloseableIterable<Entry<RecordValue<?>, Long>> groupingsInColumn = cosmos.groupResults(id, c);

        log.info(c.name() + ":");

        // Iterate over the counts, collecting the top N values in each column
        TreeMap<Long, RecordValue<?>> topValues = Maps.newTreeMap();

        for (Entry<RecordValue<?>, Long> entry : groupingsInColumn) {
            if (topValues.size() == numTopValues) {
                Entry<Long, RecordValue<?>> least = topValues.pollFirstEntry();

                if (least.getKey() < entry.getValue()) {
                    topValues.put(entry.getValue(), entry.getKey());
                } else {
                    topValues.put(least.getKey(), least.getValue());
                }
            } else if (topValues.size() < numTopValues) {
                topValues.put(entry.getValue(), entry.getKey());
            }
        }

        for (Long key : topValues.descendingKeySet()) {
            log.info(topValues.get(key).value() + " occurred " + key + " times");
        }

        sw.stop();

        log.info("Took " + sw.toString() + " to run query.\n");
    }

    log.info("Deleting records");

    // Delete the records we've ingested
    if (!example.useMiniAccumuloCluster) {
        // Because I'm lazy and don't want to wait around to run the BatchDeleter when we're just going
        // to rm -rf the directory in a few secs.
        cosmos.delete(id);
    }

    // And shut down Cosmos
    cosmos.close();

    log.info("Cosmos stopped");

    // If we were using MAC, also stop that
    if (example.useMiniAccumuloCluster && null != mac) {
        mac.stop();
        if (null != macDir) {
            FileUtils.deleteDirectory(macDir);
        }
    }
}

From source file:uk.ac.liverpool.narrative.BranchingStoryGenerator.java

public static void main(String args[]) {
    // try {Thread.sleep(10000);
    ////  w ww  . j  a  v  a 2 s .  c o  m
    // } catch (Exception x) {};

    Stopwatch s = new Stopwatch();
    s.start();
    EPSILON = EPSILON.setScale(2, BigDecimal.ROUND_HALF_EVEN);
    MAX_DURATION = MAX_DURATION.setScale(2, BigDecimal.ROUND_HALF_EVEN);

    BranchingStoryGenerator planner = new BranchingStoryGenerator();
    planner.current = Thread.currentThread();
    JCommander jc = new JCommander(planner);
    jc.setProgramName("BranchingStoryGenerator");
    try {
        jc.parse(args);
    } catch (ParameterException x) {
        jc.usage();
        usage();
        System.out.println(x.getMessage());
        System.exit(-1);
    }
    usage();
    // reminder: this seems to rule out many new solutions when run on
    // branching EHCSearch! So leave to false
    // check
    planner.doFilterReachableFacts = false;

    System.out.println("Current invocation:");
    CURRENT_ARGS = Arrays.toString(args);
    System.out.println(CURRENT_ARGS);
    if (planner.domainFilePath == null || planner.problemFilePath == null || planner.templateFilePath == null) {
        // usage();
        System.exit(-1);
    }

    planner.post_process_options();
    planner.plan(planner.problemFile);
    System.out.println("Planning took: " + s.toString());

}