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

 

转载于:https://www.cnblogs.com/yangzhilong/p/9396031.html

你可能感兴趣的:(java)