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

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

Introduction

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

Prototype

public Stopwatch start() 

Source Link

Document

Starts the stopwatch.

Usage

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();

    if (args.length != 2) {
        timer.stop();//from w w  w . j  a  v a  2s. c  o  m
        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.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();//from w ww .jav  a  2  s .  co  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: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  w w .  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);
    ///*www.  j  av  a 2 s  . c  om*/
    // } 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());

}

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();
        final ClosedCPPSolution<MazeNode> closedCPPSolution = that.solve(maze);
        stopwatch.stop();//from   w  w  w  . j  av  a  2  s  .c o  m

        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:GuavaStopwatch.java

private static void demonstrateStopwatch() {
    Stopwatch stopWatch = new Stopwatch();
    System.out.println("Is stopwatch running? " + stopWatch.isRunning());

    stopWatch.start();

    for (int i = 0; i < 1000; i++) {
        System.out.println("Is stopwatch running? " + stopWatch.isRunning());
    }//  w  ww  . j  av a  2 s. c om

    stopWatch.stop();
    System.out.println("Our loop took : " + stopWatch.elapsedTime(TimeUnit.MILLISECONDS) + " milliseconds");
}

From source file:org.glowroot.jvm.LazyPlatformMBeanServer.java

@VisibleForTesting
static void waitForJBossModuleInitialization(Stopwatch stopwatch) throws InterruptedException {
    stopwatch.start();
    while (stopwatch.elapsed(SECONDS) < 60) {
        if (System.getProperty("java.util.logging.manager") != null) {
            return;
        }/*ww  w  .  ja  v a  2 s  .c o m*/
        Thread.sleep(100);
    }
    // something has gone wrong
    logger.error("this jvm appears to be running jboss-modules, but it did not set up"
            + " java.util.logging.manager");
}

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();

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

    timer.stop();/*from  w  w w .j  a  v a2 s  .  c om*/
    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.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();
        future.get(currentTimeout, MILLIS_UNIT);
        sw.stop();//from  w  w  w.  j a  v a2 s .c  om

        long elapsed = sw.elapsed(MILLIS_UNIT);

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

        currentTimeout = milliTimeout - elapsed;
    }
}

From source file:org.eclipse.viatra.dse.monitor.PerformanceMonitorManager.java

public static void startTimer(String name) {
    Stopwatch stopwatch = Stopwatch.createUnstarted();
    timers.put(name + Thread.currentThread().getId(), stopwatch);
    stopwatch.start();
}