com.google.common.base.Stopwatch.createStarted()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(12.6k)|赞(0)|评价(0)|浏览(109)

本文整理了Java中com.google.common.base.Stopwatch.createStarted()方法的一些代码示例,展示了Stopwatch.createStarted()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Stopwatch.createStarted()方法的具体详情如下:
包路径:com.google.common.base.Stopwatch
类名称:Stopwatch
方法名:createStarted

Stopwatch.createStarted介绍

[英]Creates (and starts) a new stopwatch using System#nanoTimeas its time source.
[中]创建(并启动)一个新的秒表,使用System#NanoTimes作为其时间源。

代码示例

代码示例来源:origin: alibaba/nacos

@Override
  public void run() {
    LOGGER.info("[capacityManagement] start correct usage");
    Stopwatch stopwatch = Stopwatch.createStarted();
    correctUsage();
    LOGGER.info("[capacityManagement] end correct usage, cost: {}s", stopwatch.elapsed(TimeUnit.SECONDS));
  }
}, PropertyUtil.getCorrectUsageDelay(), PropertyUtil.getCorrectUsageDelay(), TimeUnit.SECONDS);

代码示例来源:origin: Graylog2/graylog2-server

@Override
public void retain(String indexName, IndexSet indexSet) {
  final Stopwatch sw = Stopwatch.createStarted();
  indices.delete(indexName);
  auditEventSender.success(AuditActor.system(nodeId), ES_INDEX_RETENTION_DELETE, ImmutableMap.of(
      "index_name", indexName,
      "retention_strategy", this.getClass().getCanonicalName()
  ));
  LOG.info("Finished index retention strategy [delete] for index <{}> in {}ms.", indexName,
      sw.stop().elapsed(TimeUnit.MILLISECONDS));
}

代码示例来源:origin: apache/geode

@Override
public Void call() throws Exception {
 Stopwatch timeRun = duration != DEFAULT_DURATION ? Stopwatch.createStarted() : null;
 int numRuns = 0;
 do {
  numRuns++;
  callAndValidate();
 } while ((iterations != DEFAULT_ITERATIONS && numRuns < iterations) ||
   (duration != DEFAULT_DURATION
     && timeRun.elapsed(SECONDS) <= duration.getSeconds()));
 return null;
}

代码示例来源:origin: lenskit/lenskit

void predict(RatingPredictor pred, DataAccessObject dao, long user, List<Long> items, TableWriter outW) throws IOException {
  logger.info("predicting {} items", items.size());
  Stopwatch timer = Stopwatch.createStarted();
  Map<Long, Double> preds = pred.predict(user, items);
  System.out.format("predictions for user %d:%n", user);
  for (Map.Entry<Long, Double> e : preds.entrySet()) {
    if (outW != null) {
      outW.writeRow(user, e.getKey(), e.getValue());
    }
    System.out.format("  %d", e.getKey());
    Entity item = dao.lookupEntity(CommonTypes.ITEM, e.getKey());
    String name = item == null ? null : item.maybeGet(CommonAttributes.NAME);
    if (name != null) {
      System.out.format(" (%s)", name);
    }
    System.out.format(": %.3f", e.getValue());
    System.out.println();
  }
  timer.stop();
  logger.info("predicted for {} items in {}", items.size(), timer);
}

代码示例来源:origin: palantir/atlasdb

private Map<byte[], List<Map.Entry<Cell, Value>>> getFirstRowsColumnRangePage(
    TableReference tableRef,
    List<byte[]> rows,
    BatchColumnRangeSelection columnRangeSelection,
    long ts) {
  Stopwatch watch = Stopwatch.createStarted();
  try {
    return extractRowColumnRangePage(tableRef, columnRangeSelection, ts, rows);
  } finally {
    log.debug("Call to KVS.getFirstRowColumnRangePage on table {} took {} ms.",
        tableRef, watch.elapsed(TimeUnit.MILLISECONDS));
  }
}

代码示例来源:origin: twitter/distributedlog

logger.info("Handshaking with {} hosts.", hostsSnapshot.size());
final CountDownLatch latch = new CountDownLatch(hostsSnapshot.size());
final Stopwatch stopwatch = Stopwatch.createStarted();
for (SocketAddress host: hostsSnapshot) {
  final SocketAddress address = host;

代码示例来源:origin: thinkaurelius/titan

@Override
  public IDBlock call() {
    Stopwatch running = Stopwatch.createStarted();
    try {
      if (stopRequested) {
        log.debug("Aborting ID block retrieval on partition({})-namespace({}) after " +
            "graceful shutdown was requested, exec time {}, exec+q time {}",
            partition, idNamespace, running.stop(), alive.stop());
        throw new TitanException("ID block retrieval aborted by caller");
      }
      IDBlock idBlock = idAuthority.getIDBlock(partition, idNamespace, renewTimeout);
      log.debug("Retrieved ID block from authority on partition({})-namespace({}), " +
           "exec time {}, exec+q time {}",
           partition, idNamespace, running.stop(), alive.stop());
      Preconditions.checkArgument(idBlock!=null && idBlock.numIds()>0);
      return idBlock;
    } catch (BackendException e) {
      throw new TitanException("Could not acquire new ID block from storage", e);
    } catch (IDPoolExhaustedException e) {
      return ID_POOL_EXHAUSTION;
    }
  }
}

代码示例来源:origin: twitter/distributedlog

lockStateExecutor, this, deserializeRecordSet, true);
sessionExpireWatcher = this.bkLedgerManager.registerExpirationHandler(this);
LOG.debug("Starting async reader at {}", startDLSN);
this.startDLSN = startDLSN;
this.scheduleDelayStopwatch = Stopwatch.createUnstarted();
this.readNextDelayStopwatch = Stopwatch.createStarted();
this.positionGapDetectionEnabled = bkdlm.getConf().getPositionGapDetectionEnabled();
this.idleErrorThresholdMillis = bkdlm.getConf().getReaderIdleErrorThresholdMillis();

代码示例来源:origin: apache/incubator-druid

@Override
public void persist(final Committer committer)
{
 final Stopwatch runExecStopwatch = Stopwatch.createStarted();
 appenderator.persistAll(committer);
 final long startDelay = runExecStopwatch.elapsed(TimeUnit.MILLISECONDS);
 metrics.incrementPersistBackPressureMillis(startDelay);
 if (startDelay > WARN_DELAY) {
  log.warn("Ingestion was throttled for [%,d] millis because persists were pending.", startDelay);
 }
 runExecStopwatch.stop();
}

代码示例来源:origin: thinkaurelius/titan

private synchronized void waitForIDBlockGetter() throws InterruptedException {
  Stopwatch sw = Stopwatch.createStarted();
  if (null != idBlockFuture) {
    try {
    } catch (ExecutionException e) {
      String msg = String.format("ID block allocation on partition(%d)-namespace(%d) failed with an exception in %s",
          partition, idNamespace, sw.stop());
      throw new TitanException(msg, e);
    } catch (TimeoutException e) {
      String msg = String.format("ID block allocation on partition(%d)-namespace(%d) timed out in %s",
          partition, idNamespace, sw.stop());
    } catch (CancellationException e) {
      String msg = String.format("ID block allocation on partition(%d)-namespace(%d) was cancelled after %s",
          partition, idNamespace, sw.stop());
      throw new TitanException(msg, e);
    } finally {

代码示例来源:origin: Graylog2/graylog2-server

@Override
public void retain(String indexName, IndexSet indexSet) {
  final Stopwatch sw = Stopwatch.createStarted();
  indices.close(indexName);
  auditEventSender.success(AuditActor.system(nodeId), ES_INDEX_RETENTION_CLOSE, ImmutableMap.of(
      "index_name", indexName,
      "retention_strategy", this.getClass().getCanonicalName()
  ));
  LOG.info("Finished index retention strategy [close] for index <{}> in {}ms.", indexName,
      sw.stop().elapsed(TimeUnit.MILLISECONDS));
}

代码示例来源:origin: twitter/distributedlog

@Override
  public T apply() {
    taskPendingTime.registerSuccessfulEvent(pendingStopwatch.elapsed(TimeUnit.MICROSECONDS));
    Stopwatch executionStopwatch = Stopwatch.createStarted();
    T result = function0.apply();
    taskExecutionTime.registerSuccessfulEvent(executionStopwatch.elapsed(TimeUnit.MICROSECONDS));
    long elapsed = executionStopwatch.elapsed(TimeUnit.MICROSECONDS);
    if (elapsed > traceTaskExecutionWarnTimeUs) {
      LOG.info("{} took too long {} microseconds", function0.toString(), elapsed);
    }
    return result;
  }
}

代码示例来源:origin: lenskit/lenskit

public LenskitRecommenderEngine loadEngine() throws RecommenderBuildException, IOException {
  File modelFile = options.get("model_file");
  if (modelFile == null) {
    logger.info("creating fresh recommender");
    LenskitRecommenderEngineBuilder builder = LenskitRecommenderEngine.newBuilder();
    for (LenskitConfiguration config: environment.loadConfigurations(getConfigFiles())) {
      builder.addConfiguration(config);
    Stopwatch timer = Stopwatch.createStarted();
    LenskitRecommenderEngine engine = builder.build(input.getDAO());
    timer.stop();
    logger.info("built recommender in {}", timer);
    return engine;
  } else {
    logger.info("loading recommender from {}", modelFile);
    LenskitRecommenderEngineLoader loader = LenskitRecommenderEngine.newLoader();
    loader.setClassLoader(environment.getClassLoader());
      loader.addConfiguration(config);
    Stopwatch timer = Stopwatch.createStarted();
    LenskitRecommenderEngine engine;
    InputStream input = new FileInputStream(modelFile);
      input.close();
    timer.stop();
    logger.info("loaded recommender in {}", timer);
    return engine;

代码示例来源:origin: palantir/atlasdb

private TokenBackedBasicResultsPage<RowResult<Set<Long>>, Token> getTimestampsPage(
    TableReference tableRef,
    RangeRequest range,
    long timestamp,
    long batchSize,
    Token token) {
  Stopwatch watch = Stopwatch.createStarted();
  try {
    return runRead(tableRef, table -> getTimestampsPageInternal(table, range, timestamp, batchSize, token));
  } finally {
    log.debug("Call to KVS.getTimestampsPage on table {} took {} ms.",
        tableRef, watch.elapsed(TimeUnit.MILLISECONDS));
  }
}

代码示例来源:origin: kairosdb/kairosdb

@Override
public void run()
{
  logger.info("Loading one year of demo data...");
  long now = new DateTime().getMillis();
  long insertTime = new DateTime().minusDays(365).getMillis();
  long startTime = insertTime;
  double period = 86400000.0;
  Stopwatch timer = Stopwatch.createStarted();
  while (m_keepRunning && insertTime < now)
  {
    for (int I = 0; I < m_numberOfRows; I++)
    {
      double value = ((double)(insertTime-startTime) / period) + ((double)I / (double)m_numberOfRows);
      //System.out.println(value);
      value = Math.sin(value * 2.0 * Math.PI);
      //System.out.println(value);
      DataPoint dataPoint = m_doubleDataPointFactory.createDataPoint(insertTime, value);
      ImmutableSortedMap<String, String> tags = ImmutableSortedMap.of("host", "demo_server_"+I);
      DataPointEvent dataPointEvent = new DataPointEvent(m_metricName, tags, dataPoint, m_ttl);
      m_publisher.post(dataPointEvent);
      m_counter++;
    }
    insertTime += 60000; //Advance 1 minute
  }
}

代码示例来源:origin: JanusGraph/janusgraph

@Override
  public IDBlock call() {
    Stopwatch running = Stopwatch.createStarted();
    try {
      if (stopRequested) {
        log.debug("Aborting ID block retrieval on partition({})-namespace({}) after " +
            "graceful shutdown was requested, exec time {}, exec+q time {}",
            partition, idNamespace, running.stop(), alive.stop());
        throw new JanusGraphException("ID block retrieval aborted by caller");
      }
      IDBlock idBlock = idAuthority.getIDBlock(partition, idNamespace, renewTimeout);
      log.debug("Retrieved ID block from authority on partition({})-namespace({}), " +
           "exec time {}, exec+q time {}",
           partition, idNamespace, running.stop(), alive.stop());
      Preconditions.checkArgument(idBlock!=null && idBlock.numIds()>0);
      return idBlock;
    } catch (BackendException e) {
      throw new JanusGraphException("Could not acquire new ID block from storage", e);
    } catch (IDPoolExhaustedException e) {
      return ID_POOL_EXHAUSTION;
    }
  }
}

代码示例来源:origin: twitter/distributedlog

void complete() {
    if (LOG.isTraceEnabled()) {
      LOG.trace("{} : Satisfied promise with {} records", bkLedgerManager.getFullyQualifiedName(), records.size());
    }
    delayUntilPromiseSatisfied.registerSuccessfulEvent(enqueueTime.stop().elapsed(TimeUnit.MICROSECONDS));
    Stopwatch stopwatch = Stopwatch.createStarted();
    promise.setValue(records);
    futureSetLatency.registerSuccessfulEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
  }
}

代码示例来源:origin: twitter/distributedlog

@Override
public byte[] compress(byte[] data, int offset, int length, OpStatsLogger compressionStat) {
  Preconditions.checkNotNull(data);
  Preconditions.checkArgument(offset >= 0 && offset < data.length);
  Preconditions.checkArgument(length >= 0);
  Preconditions.checkNotNull(compressionStat);
  Stopwatch watch = Stopwatch.createStarted();
  byte[] compressed = compressor.compress(data, offset, length);
  compressionStat.registerSuccessfulEvent(watch.elapsed(TimeUnit.MICROSECONDS));
  return compressed;
}

代码示例来源:origin: JanusGraph/janusgraph

private synchronized void waitForIDBlockGetter() throws InterruptedException {
  Stopwatch sw = Stopwatch.createStarted();
  if (null != idBlockFuture) {
    try {
    } catch (ExecutionException e) {
      String msg = String.format("ID block allocation on partition(%d)-namespace(%d) failed with an exception in %s",
          partition, idNamespace, sw.stop());
      throw new JanusGraphException(msg, e);
    } catch (TimeoutException e) {
      String msg = String.format("ID block allocation on partition(%d)-namespace(%d) timed out in %s",
          partition, idNamespace, sw.stop());
    } catch (CancellationException e) {
      String msg = String.format("ID block allocation on partition(%d)-namespace(%d) was cancelled after %s",
          partition, idNamespace, sw.stop());
      throw new JanusGraphException(msg, e);
    } finally {

代码示例来源:origin: Graylog2/graylog2-server

@Override
  protected void shutDown() throws Exception {
    for (Periodical periodical : periodicals.getAllStoppedOnGracefulShutdown()) {
      LOG.info("Shutting down periodical [{}].", periodical.getClass().getCanonicalName());
      Stopwatch s = Stopwatch.createStarted();

      // Cancel future executions.
      Map<Periodical,ScheduledFuture> futures = periodicals.getFutures();
      if (futures.containsKey(periodical)) {
        futures.get(periodical).cancel(false);

        s.stop();
        LOG.info("Shutdown of periodical [{}] complete, took <{}ms>.",
            periodical.getClass().getCanonicalName(), s.elapsed(TimeUnit.MILLISECONDS));
      } else {
        LOG.error("Could not find periodical [{}] in futures list. Not stopping execution.",
            periodical.getClass().getCanonicalName());
      }
    }
  }
}

相关文章