List of usage examples for com.google.common.base Stopwatch createStarted
@CheckReturnValue public static Stopwatch createStarted()
From source file:org.grouplens.lenskit.cli.GlobalRecommend.java
@Override public void execute() throws IOException, RecommenderBuildException { LenskitRecommenderEngine engine = loader.loadEngine(); List<Long> items = options.get("items"); final int n = options.getInt("num_recs"); LenskitRecommender rec = engine.createRecommender(); GlobalItemRecommender irec = rec.getGlobalItemRecommender(); ItemNameDAO indao = rec.get(ItemNameDAO.class); if (irec == null) { logger.error("recommender has no global recommender"); throw new UnsupportedOperationException("no global recommender"); }/*from w w w . j a v a2 s . com*/ logger.info("using {} reference items", items.size()); Symbol pchan = getPrintChannel(); Stopwatch timer = Stopwatch.createStarted(); List<ScoredId> recs = irec.globalRecommend(LongUtils.packedSet(items), n); for (ScoredId item : recs) { System.out.format("%d", item.getId()); if (indao != null) { System.out.format(" (%s)", indao.getItemName(item.getId())); } System.out.format(": %.3f", item.getScore()); if (pchan != null && item.hasUnboxedChannel(pchan)) { System.out.format(" (%f)", item.getUnboxedChannelValue(pchan)); } System.out.println(); } timer.stop(); logger.info("recommended in {}", timer); }
From source file:io.mandrel.worker.Barrier.java
public void passOrWait(Long consumedSize) { Stopwatch stopwatch = Stopwatch.createStarted(); pagePageRateBucket.consume();/* w ww. ja v a 2s. co m*/ if (consumedSize != null) { bandwidthBucket.consume(consumedSize.longValue()); } long elapsed = stopwatch.stop().elapsed(TimeUnit.SECONDS); if (politeness.getWait() > 0 && politeness.getWait() > elapsed) { Uninterruptibles.sleepUninterruptibly(politeness.getWait() - elapsed, TimeUnit.SECONDS); } }
From source file:com.fireball1725.firelib.FireMod.java
@Mod.EventHandler public final void init(FMLInitializationEvent event) { final Stopwatch stopwatch = Stopwatch.createStarted(); this.getLogger().info("Initialization (Started)"); proxy().initStart(event);//from w w w .j a va 2s . c o m proxy().registerCapabilities(); proxy().registerEventHandlers(); proxy().initEnd(event); this.getLogger().info("Initialization (Ended after " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "ms)"); }
From source file:org.locationtech.geogig.plumbing.index.BuildIndexOp.java
@Override protected RevTree _call() { checkState(index != null, "index to update was not provided"); checkState(oldCanonicalTree != null, "old canonical version of the tree was not provided"); checkState(newCanonicalTree != null, "new canonical version of the tree was not provided"); checkState(revFeatureTypeId != null, "FeatureType id was not provided"); final RevTreeBuilder builder = resolveTreeBuilder(); final PreOrderDiffWalk.Consumer builderConsumer = resolveConsumer(builder); boolean preserveIterationOrder = true; final ObjectDatabase canonicalStore = objectDatabase(); PreOrderDiffWalk walk = new PreOrderDiffWalk(oldCanonicalTree, newCanonicalTree, canonicalStore, canonicalStore, preserveIterationOrder); final ProgressListener progress = getProgressListener(); final Stopwatch dagTime = Stopwatch.createStarted(); walk.walk(builderConsumer);//from w ww. ja v a2 s . c o m dagTime.stop(); if (progress.isCanceled()) { return null; } progress.setDescription(String.format("Index updated in %s. Building final tree...", dagTime)); final Stopwatch revTreeTime = Stopwatch.createStarted(); RevTree indexTree; try { indexTree = builder.build(); } catch (Exception e) { e.printStackTrace(); throw Throwables.propagate(Throwables.getRootCause(e)); } revTreeTime.stop(); indexDatabase().addIndexedTree(index, newCanonicalTree.getId(), indexTree.getId()); progress.setDescription( String.format("QuadTree created. Size: %,d, time: %s", indexTree.size(), revTreeTime)); progress.complete(); return indexTree; }
From source file:com.dssmp.agent.tailing.AsyncPublisher.java
/** * @param timeout Use a value {@code <= 0} to wait indefinitely. * @param unit/*from w w w. j a va 2 s . co m*/ * @return {@code true} if idle state was reached before the timeout * expired, or {@code false} if idle state was not successfully * reached. */ public boolean waitForIdle(long timeout, TimeUnit unit) { Stopwatch timer = Stopwatch.createStarted(); while (!isIdle()) { long remaining = timeout > 0 ? (unit.toMillis(timeout) - timer.elapsed(TimeUnit.MILLISECONDS)) : Long.MAX_VALUE; if (remaining <= 0) return false; long sleepTime = Math.min(MAX_SPIN_WAIT_TIME_MILLIS, remaining); logger.trace("{}: Waiting for idle state. Sleeping {}ms. {}", name(), sleepTime, toString()); // Perform a check on any pending records in case it's time to publish them before sleeping queue.checkPendingRecords(); try { Thread.sleep(sleepTime); } catch (InterruptedException e) { // No need to make this method interruptible. Just return false signifying timeout. Thread.currentThread().interrupt(); logger.trace("{}: Thread interrupted.", name(), e); return false; } } return true; }
From source file:org.hyperledger.perftest.SendTransactionThroughputMeasure.java
private List<Long> measureSingleThreaded() throws Exception { List<Long> results = new ArrayList<>(getRounds()); for (int i = 0; i < getRounds(); i++) { System.out.println("Measuring round " + i); List<Transaction> txsForOneRound = txs.get(i); System.gc();/*from ww w . j a v a 2 s.c om*/ System.gc(); System.gc(); System.gc(); System.gc(); Stopwatch watch = Stopwatch.createStarted(); for (Transaction tx : txsForOneRound) { api.sendTransaction(tx); } watch.stop(); results.add(watch.elapsed(TimeUnit.MILLISECONDS)); } return results; }
From source file:org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats.java
private OnDemandRaftState getOnDemandRaftState() { String name = getShardName(); OnDemandRaftState state = onDemandRaftStateCache.getIfPresent(name); if (state == null) { statRetrievalError = null;// w w w . jav a 2s . co m statRetrievalTime = null; if (shard != null) { Timeout timeout = new Timeout(10, TimeUnit.SECONDS); try { Stopwatch timer = Stopwatch.createStarted(); state = (OnDemandRaftState) Await.result( Patterns.ask(shard.getSelf(), GetOnDemandRaftState.INSTANCE, timeout), timeout.duration()); statRetrievalTime = timer.stop().toString(); onDemandRaftStateCache.put(name, state); } catch (Exception e) { statRetrievalError = e.toString(); } } state = state != null ? state : OnDemandRaftState.builder().build(); } return state; }
From source file:es.usc.citius.composit.wsc08.data.knowledge.WSCXMLKnowledgeBase.java
private void initialize() { // Load all superclasses, subclasses and instances logger.debug("Initializing WSCXMLKnowledgeBase (root concept {})", taxonomy.getConcept().getID()); Stopwatch stopwatch = Stopwatch.createStarted(); populate(taxonomy.getConcept());/*from www . ja v a 2 s . c om*/ logger.debug("Knowledge base created in {}. Total concepts {}.", stopwatch.stop().toString(), conceptID.keySet().size()); }
From source file:org.opendaylight.controller.dummy.datastore.DummyShard.java
protected void handleAppendEntries(AppendEntries req) throws InterruptedException { LOG.info("{} - Received AppendEntries message : leader term = {}, index = {}, prevLogIndex = {}, size = {}", followerId, req.getTerm(), req.getLeaderCommit(), req.getPrevLogIndex(), req.getEntries().size()); if (appendEntriesWatch != null) { long elapsed = appendEntriesWatch.elapsed(TimeUnit.SECONDS); if (elapsed >= 5) { LOG.error(//from www. j a va 2s .c om "More than 5 seconds since last append entry, elapsed Time = {} seconds" + ", leaderCommit = {}, prevLogIndex = {}, size = {}", elapsed, req.getLeaderCommit(), req.getPrevLogIndex(), req.getEntries().size()); } appendEntriesWatch.reset().start(); } else { appendEntriesWatch = Stopwatch.createStarted(); } if (lastMessageIndex == req.getLeaderCommit() && req.getEntries().size() > 0 && lastMessageSize > 0) { LOG.error("{} - Duplicate message with leaderCommit = {} prevLogIndex = {} received", followerId, req.getLeaderCommit(), req.getPrevLogIndex()); } lastMessageIndex = req.getLeaderCommit(); lastMessageSize = req.getEntries().size(); long lastIndex = req.getLeaderCommit(); if (req.getEntries().size() > 0) { for (ReplicatedLogEntry entry : req.getEntries()) { lastIndex = entry.getIndex(); } } if (configuration.shouldCauseTrouble() && req.getEntries().size() > 0) { boolean ignore = false; if (configuration.shouldDropReplies()) { ignore = Math.random() > 0.5; } long delay = (long) (Math.random() * configuration.getMaxDelayInMillis()); if (!ignore) { LOG.info("{} - Randomizing delay : {}", followerId, delay); Thread.sleep(delay); sender().tell(new AppendEntriesReply(followerId, req.getTerm(), true, lastIndex, req.getTerm(), DataStoreVersions.CURRENT_VERSION), self()); } } else { sender().tell(new AppendEntriesReply(followerId, req.getTerm(), true, lastIndex, req.getTerm(), DataStoreVersions.CURRENT_VERSION), self()); } }
From source file:com.google.cloud.examples.nio.ParallelCountBytes.java
/** * Print the length and MD5 of the indicated file. * * <p>This uses the normal Java NIO Api, so it can take advantage of any installed * NIO Filesystem provider without any extra effort. *///from w w w . j a va2s .c o m private static void countFile(String fname) throws Exception { // large buffers pay off final int bufSize = 50 * 1024 * 1024; Queue<Future<WorkUnit>> work = new ArrayDeque<>(); Path path = Paths.get(new URI(fname)); long size = Files.size(path); System.out.println(fname + ": " + size + " bytes."); int nThreads = (int) Math.ceil(size / (double) bufSize); if (nThreads > 4) nThreads = 4; System.out.println("Reading the whole file using " + nThreads + " threads..."); Stopwatch sw = Stopwatch.createStarted(); long total = 0; MessageDigest md = MessageDigest.getInstance("MD5"); ExecutorService exec = Executors.newFixedThreadPool(nThreads); int blockIndex; for (blockIndex = 0; blockIndex < nThreads; blockIndex++) { work.add(exec.submit(new WorkUnit(Files.newByteChannel(path), bufSize, blockIndex))); } while (!work.isEmpty()) { WorkUnit full = work.remove().get(); md.update(full.buf.array(), 0, full.buf.position()); total += full.buf.position(); if (full.buf.hasRemaining()) { full.close(); } else { work.add(exec.submit(full.resetForIndex(blockIndex++))); } } exec.shutdown(); long elapsed = sw.elapsed(TimeUnit.SECONDS); System.out.println("Read all " + total + " bytes in " + elapsed + "s. "); String hex = String.valueOf(BaseEncoding.base16().encode(md.digest())); System.out.println("The MD5 is: 0x" + hex); if (total != size) { System.out.println("Wait, this doesn't match! We saw " + total + " bytes, " + "yet the file size is listed at " + size + " bytes."); } }