我怎么知道我的秒表已经运行了?

时间:2014-03-18 12:54:33

标签: guava

我在我的应用程序中使用了几个秒表。它们都是一起创建的,但实际上只有部分实际运行(由于代码或其他东西中的例外)。

我的应用程序运行后,我正在使用这些秒表创建报告。例如,我正在做以下事情:

Stopwatch subStopwatch = Stopwatch.createUnstarted();
Stopwatch mainStopwatch = Stopwatch.createStarted();
try {
  // do something 1
  subStopwatch.start();
  // do something 2
  subStopwatch.stop();
} finally {
  mainStopwatch.stop();
  System.out.printf("Total run time: %s%n",  mainStopwatch);
  if (!subStopwatch.isRunning()) {
    System.out.printf("  including sub run time: %s%n", subStopwatch);
  }
}

此代码中的问题是,如果“执行某事1”(返回,异常)中发生某些事情,则无论如何都会打印subStopwatch。

以下解决方案有效: - 使用布尔值表示我启动了秒表。 - 在本地使用秒表并使用包含我正在寻找的信息的报告机制。

但主要问题仍然存在:我是否知道秒表仅使用秒表运行。

1 个答案:

答案 0 :(得分:1)

您可以查看秒表上的elapsed time

if (subStopwatch.elapsed(TimeUnit.NANOSECONDS) > 0) {
    // it ran
}