Guava Stopwatch

Stopwatch 解释为计时器,又称秒表、停表,是记录时间的。

 

使用System.currentTimeMillis()也能统计这段代码的执行时间,那么为什么还会有Stopwatch

官方称不直接使用System#nanoTime是有一下几个原因:

  • 时间源可以替代 可以重写Ticker

  • nanoTime的返回值是纳秒,返回的值没有意义,Stopwatch抽象返回值

 

Stopwatch stopwatch = Stopwatch.createStarted();

long startTime = System.currentTimeMillis();
for (long i = 0; i < 1000000000L; i++) {
    // do some thing
}
System.out.println("逻辑代码运行耗时:" + stopwatch.elapsed(TimeUnit.MILLISECONDS));
System.out.println(System.currentTimeMillis() - startTime);

// stopwatch.stop();//暂停
stopwatch.reset();//重置
stopwatch.start();//启动
for (long i = 0; i < 1000000000L; i++) {
    // do some thing
}
System.out.println("逻辑代码运行耗时:" + stopwatch.elapsed(TimeUnit.MILLISECONDS));
System.out.println(System.currentTimeMillis() - startTime);

for (long i = 0; i < 1000000000L; i++) {
    // do some thing
}
System.out.println("逻辑代码运行耗时:" + stopwatch.elapsed(TimeUnit.MILLISECONDS));
System.out.println(System.currentTimeMillis() - startTime);

 

posted @ 2021-07-14 15:20  草木物语  阅读(484)  评论(0编辑  收藏  举报