1. 程式人生 > >Guava之計時器Stopwatch

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