Guava之计时器Stopwatch

 1 import java.util.concurrent.TimeUnit;
 2 
 3 import org.junit.Test;
 4 
 5 import com.google.common.base.Stopwatch;
 6 
 7 public class GuavaTest {
 8     
 9     @Test
10     public void testStopwatch() throws InterruptedException {
11         // 创建自动start的计时器
12         Stopwatch watch = Stopwatch.createStarted();
13         Thread.sleep(1000L);
14         long time = watch.elapsed(TimeUnit.MILLISECONDS);
15         // 结果1003
16         System.out.println("代码执行时长:" + time);
17         
18         // 创建非自动start的计时器
19         // 累计了start到stop的时间
20         Stopwatch watch1 = Stopwatch.createUnstarted();
21         watch1.start();
22         Thread.sleep(1000L);
23         watch1.stop();
24         watch1.start();
25         Thread.sleep(500L);
26         time = watch1.elapsed(TimeUnit.MILLISECONDS);
27         // 结果1500
28         System.out.println("代码执行时长:" + time);
29         
30         Stopwatch watch2 = Stopwatch.createUnstarted();
31         watch2.start();
32         Thread.sleep(1000L);
33         time = watch2.elapsed(TimeUnit.MILLISECONDS);
34         // 结果1000
35         System.out.println("代码执行时长:" + time);
36     }
37 }

执行结果(不同机器执行结果可能有差异):

代码执行时长:1003
代码执行时长:1500
代码执行时长:1000

 

posted @ 2018-07-31 15:19  自行车上的程序员  阅读(9507)  评论(0编辑  收藏  举报