org.apache.commons.lang3.time.StopWatch类的使用及代码示例

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

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

StopWatch介绍

[英]StopWatch provides a convenient API for timings.

To start the watch, call #start() or StopWatch#createStarted(). At this point you can:

  • #split() the watch to get the time whilst the watch continues in the background. #unsplit() will remove the effect of the split. At this point, these three options are available again.
  • #suspend() the watch to pause it. #resume() allows the watch to continue. Any time between the suspend and resume will not be counted in the total. At this point, these three options are available again.
  • #stop() the watch to complete the timing session.

It is intended that the output methods #toString() and #getTime() should only be called after stop, split or suspend, however a suitable result will be returned at other points.

NOTE: As from v2.1, the methods protect against inappropriate calls. Thus you cannot now call stop before start, resume before suspend or unsplit before split.

  1. split(), suspend(), or stop() cannot be invoked twice
  2. unsplit() may only be called if the watch has been split()
  3. resume() may only be called if the watch has been suspend()
  4. start() cannot be called twice without calling reset()

This class is not thread-safe
[中]StopWatch为计时提供了方便的API。
要启动手表,请调用#start()或秒表#createStarted()。此时,您可以:
*#分割()手表以获取时间,同时手表继续在后台运行#unsplit()将删除拆分的效果。此时,这三个选项再次可用。
*挂起手表暂停#resume()允许手表继续运行。暂停和恢复之间的任何时间都不计入总数。此时,这三个选项再次可用。
*#停止()手表以完成计时任务。
输出方法#toString()和#getTime()只应在stop、split或suspend之后调用,但是会在其他点返回合适的结果。
注:从v2开始。1.这些方法可以防止不适当的调用。因此,您现在不能在开始之前调用stop,在暂停之前调用resume,或者在拆分之前调用unsplit。
1.split()、suspend()或stop()不能被调用两次
2.unsplit()只能在手表已拆分时调用()
3.仅当手表已暂停()时,才能调用resume()
4.在不调用reset()的情况下,无法调用start()两次
这个类不是线程安全的

代码示例

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

@Override public Void call() throws Exception {
  ZooKeeper zooKeeper = null;
  try {
   zooKeeper = new ZooKeeper(host, timeout, EmptyWatcher.instance);
   Stat exists = zooKeeper.exists(znode, false);
   StopWatch stopwatch = new StopWatch();
   stopwatch.start();
   zooKeeper.getData(znode, false, exists);
   stopwatch.stop();
   sink.publishReadTiming(znode, host, stopwatch.getTime());
  } catch (KeeperException | InterruptedException e) {
   sink.publishReadFailure(znode, host);
  } finally {
   if (zooKeeper != null) {
    zooKeeper.close();
   }
  }
  return null;
 }
}

代码示例来源:origin: org.apache.commons/commons-lang3

@Test
public void testGetStartTime() {
  final long beforeStopWatch = System.currentTimeMillis();
  final StopWatch watch = new StopWatch();
  try {
    watch.getStartTime();
    fail("Calling getStartTime on an unstarted StopWatch should throw an exception");
  } catch (final IllegalStateException expected) {
    // expected
  }
  watch.start();
  try {
    watch.getStartTime();
    assertTrue(watch.getStartTime() >= beforeStopWatch);
  } catch (final IllegalStateException ex) {
    fail("Start time should be available: " + ex.getMessage());
  }
  watch.reset();
  try {
    watch.getStartTime();
    fail("Calling getStartTime on a reset, but unstarted StopWatch should throw an exception");
  } catch (final IllegalStateException expected) {
    // expected
  }
}

代码示例来源:origin: org.apache.commons/commons-lang3

@Test
public void testStopWatchSimpleGet() {
  final StopWatch watch = new StopWatch();
  assertEquals(0, watch.getTime());
  assertEquals("00:00:00.000", watch.toString());
  watch.start();
  try {
    Thread.sleep(500);
  } catch (final InterruptedException ex) {
  }
  assertTrue(watch.getTime() < 2000);
}

代码示例来源:origin: org.apache.commons/commons-lang3

/**
 * Provides a started stopwatch for convenience.
 *
 * @return StopWatch a stopwatch that's already been started.
 *
 * @since 3.5
 */
public static StopWatch createStarted() {
  final StopWatch sw = new StopWatch();
  sw.start();
  return sw;
}

代码示例来源:origin: org.apache.commons/commons-lang3

@Test
public void testStopWatchSplit() {
  final StopWatch watch = new StopWatch();
  watch.start();
  try {
    Thread.sleep(550);
  } catch (final InterruptedException ex) {
  }
  watch.split();
  final long splitTime = watch.getSplitTime();
  final String splitStr = watch.toSplitString();
  try {
    Thread.sleep(550);
  } catch (final InterruptedException ex) {
  }
  watch.unsplit();
  try {
    Thread.sleep(550);
  } catch (final InterruptedException ex) {
  }
  watch.stop();
  final long totalTime = watch.getTime();
  assertEquals("Formatted split string not the correct length",
      splitStr.length(), 12);
  assertTrue(splitTime >= 500);
  assertTrue(splitTime < 700);
  assertTrue(totalTime >= 1500);
  assertTrue(totalTime < 1900);
}

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

StopWatch timer = new StopWatch();
timer.start();
assert Math.abs(itemFeatures.getColumnVector(f).getL1Norm() - ivec.getL1Norm()) < 1.0e-4 : "item column sum matches";
timer.stop();
logger.info("Finished feature {} in {} (RMSE={})", f, timer, rmse);

代码示例来源:origin: torakiki/pdfsam

@Override
public void start(Stage primaryStage) {
  this.primaryStage = primaryStage;
  injector = initInjector();
  Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionLogger());
  initSejda();
  cleanIfRequired();
  primaryStage.setScene(initScene());
  primaryStage.getIcons().addAll(injector.instancesOfType(Image.class));
  primaryStage.setTitle(injector.instance(Pdfsam.class).name());
  primaryStage.setOnCloseRequest(e -> Platform.exit());
  requestPremiumModulesDescriptionIfRequired();
  initWindowsStatusController(primaryStage);
  initDialogsOwner(primaryStage);
  initActiveModule();
  loadWorkspaceIfRequired();
  initOpenButtons();
  primaryStage.show();
  requestCheckForUpdateIfRequired();
  requestLatestNewsIfRequired();
  eventStudio().addAnnotatedListeners(this);
  closeSplash();
  STOPWATCH.stop();
  LOG.info(DefaultI18nContext.getInstance().i18n("Started in {0}",
      DurationFormatUtils.formatDurationWords(STOPWATCH.getTime(), true, true)));
  new InputPdfArgumentsController().accept(rawParameters);
}

代码示例来源:origin: opencb/opencga

@Test
  public void testSampleIterator() throws CatalogException, SolrServerException, IOException {
    MongoDBAdaptorFactory factory = new MongoDBAdaptorFactory(catalogManager.getConfiguration());
    SampleDBAdaptor sampleDBAdaptor = factory.getCatalogSampleDBAdaptor();

    QueryOptions queryOptions = new QueryOptions();
    queryOptions.add(QueryOptions.INCLUDE, Arrays.asList(SampleDBAdaptor.QueryParams.ID.key(),
        SampleDBAdaptor.QueryParams.UID.key(), SampleDBAdaptor.QueryParams.INDIVIDUAL.key() + ".id"));
    //queryOptions.add("nativeQuery", true);
    queryOptions.add("lazy", false);

    DBIterator<Sample> sampleDBIterator = sampleDBAdaptor.iterator(new Query(), queryOptions);
    int i = 0;
    StopWatch stopWatch = StopWatch.createStarted();
    while (sampleDBIterator.hasNext()) {
      Sample sample = sampleDBIterator.next();
      i++;
      if (i % 10000 == 0) {
        System.out.println("i: " + i + "; time: " + stopWatch.getTime(TimeUnit.MILLISECONDS));
        stopWatch.reset();
        stopWatch.start();
      }
//            System.out.println(sample);
//            if (sample.getAttributes() != null && sample.getAttributes().containsKey("individual")) {
//                System.out.println(sample.getAttributes().get("individual"));
//            }
    }
  }

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

dfs.recoverLease(partPath);
boolean isclosed = dfs.isFileClosed(partPath);
StopWatch sw = new StopWatch();
sw.start();
while (!isclosed) {
  if (sw.getTime() > asyncTimeout) {
    break;
StopWatch sw = new StopWatch();
sw.start();
long newLen = fs.getFileStatus(partPath).getLen();
while (newLen != validLength) {
  if (sw.getTime() > asyncTimeout) {
    break;

代码示例来源:origin: org.apache.commons/commons-lang3

@Test
public void testBooleanStates() {
  final StopWatch watch = new StopWatch();
  assertFalse(watch.isStarted());
  assertFalse(watch.isSuspended());
  assertTrue(watch.isStopped());
  watch.start();
  assertTrue(watch.isStarted());
  assertFalse(watch.isSuspended());
  assertFalse(watch.isStopped());
  watch.suspend();
  assertTrue(watch.isStarted());
  assertTrue(watch.isSuspended());
  assertFalse(watch.isStopped());
  watch.stop();
  assertFalse(watch.isStarted());
  assertFalse(watch.isSuspended());
  assertTrue(watch.isStopped());
}

代码示例来源:origin: org.apache.commons/commons-lang3

@Test
public void testBadStates() {
  final StopWatch watch = new StopWatch();
  try {
    watch.stop();
    fail("Calling stop on an unstarted StopWatch should throw an exception. ");
  } catch (final IllegalStateException ise) {
    watch.stop();
    fail("Calling stop on an unstarted StopWatch should throw an exception. ");
  } catch (final IllegalStateException ise) {
    watch.suspend();
    fail("Calling suspend on an unstarted StopWatch should throw an exception. ");
  } catch (final IllegalStateException ise) {
    watch.split();
    fail("Calling split on a non-running StopWatch should throw an exception. ");
  } catch (final IllegalStateException ise) {
    watch.unsplit();
    fail("Calling unsplit on an unsplit StopWatch should throw an exception. ");
  } catch (final IllegalStateException ise) {
    watch.resume();
    fail("Calling resume on an unsuspended StopWatch should throw an exception. ");
  } catch (final IllegalStateException ise) {
  watch.start();

代码示例来源:origin: cheng-li/pyramid

protected void skipOrUpdateBinaryClassifier(int component, int label, MultiLabelClfDataSet activeDataSet,
                      double[] activeGammas, double totalWeight){
  StopWatch stopWatch = new StopWatch();
  stopWatch.start();
    cbm.binaryClassifiers[component][label] = new PriorProbClassifier(probs);
    sb.append(", skip, use prior = ").append(smoothedPositiveProb);
    sb.append(", time spent = ").append(stopWatch.toString());
    if (logger.isDebugEnabled()){
      logger.debug(sb.toString());

代码示例来源:origin: us.ihmc/robot-environment-awareness

public void run(Runnable command, String timeReportPrefix)
  {
   if (reportTimeEnabled.get())
   {
     StopWatch stopWatch = stopWatchLocal.get();
     stopWatch.reset();
     stopWatch.start();
     command.run();
     long nanoTime = stopWatch.getNanoTime();
     if (nanoTime > minimumNanoTimeToReport.get())
      LogTools.info(timeReportPrefix + Conversions.nanosecondsToSeconds(nanoTime));
   }
   else
     command.run();
  }
}

代码示例来源:origin: winder/Universal-G-Code-Sender

this.streamStopWatch.reset();
this.streamStopWatch.start();
this.numCommands = 0;
this.numCommandsSent = 0;
} catch(Exception e) {
  this.isStreaming = false;
  this.streamStopWatch.reset();
  this.comm.cancelSend();
  throw e;

代码示例来源:origin: org.apache.commons/commons-lang3

/**
 * <p>
 * Gets a summary of the time that the stopwatch recorded as a string.
 * </p>
 *
 * <p>
 * The format used is ISO 8601-like, <i>hours</i>:<i>minutes</i>:<i>seconds</i>.<i>milliseconds</i>.
 * </p>
 *
 * @return the time as a String
 */
@Override
public String toString() {
  return DurationFormatUtils.formatDurationHMS(getTime());
}

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

@Override
public void onCompleted() {
  timer.stop();
  latch.countDown();
}

代码示例来源:origin: fhoeben/hsac-fitnesse-fixtures

private int getNextInterval(StopWatch loopTimer) {
  int nextInterval;
  long loopTime = loopTimer.getTime();
  nextInterval = Math.max(0, ((int) (repeatInterval - loopTime)));
  loopTimer.reset();
  return nextInterval;
}

代码示例来源:origin: torakiki/pdfsam

@Override
public void init() {
  STOPWATCH.start();
  rawParameters = getParameters().getRaw();
  verboseIfRequired();
  startLogAppender();
  System.setProperty(PDDocumentHandler.SAMBOX_USE_ASYNC_WRITER, Boolean.TRUE.toString());
  System.setProperty(Sejda.UNETHICAL_READ_PROPERTY_NAME, Boolean.TRUE.toString());
  LOG.info("Starting PDFsam");
  clean = rawParameters.contains("--clean") || rawParameters.contains("-clean") || rawParameters.contains("-c");
  cleanUserContextIfNeeded(userContext);
  String localeString = userContext.getLocale();
  if (isNotBlank(localeString)) {
    eventStudio().broadcast(new SetLocaleEvent(localeString));
  }
  String defaultworkingPath = userContext.getDefaultWorkingPath();
  if (isNotBlank(defaultworkingPath)) {
    try {
      if (Files.isDirectory(Paths.get(defaultworkingPath))) {
        eventStudio().broadcast(new SetLatestDirectoryEvent(new File(defaultworkingPath)));
      }
    } catch (InvalidPathException e) {
      LOG.warn("Unable to set initial directory, default path is invalid.", e);
    }
  }
}

代码示例来源:origin: stackoverflow.com

org.apache.commons.lang3.time.StopWatch sw = new StopWatch();
sw.start();     
Thread.sleep(1000 * 4);     
sw.stop();
System.out.println("Apache StopWatch  : "+ millisToShortDHMS(sw.getTime()) );

代码示例来源:origin: ru.vyarus/dropwizard-guicey

@Override
public void lifeCycleStopping(final LifeCycle event) {
  timer.reset();
  log("Stopping Jetty...");
}

相关文章