第一種使用spring的java
import java.util.concurrent.TimeUnit; import org.springframework.util.StopWatch; public class Test { public static void main(String[] args) throws InterruptedException { testSpringStopwatch(); } private static void testSpringStopwatch() throws InterruptedException { StopWatch s = new StopWatch(); s.start(); TimeUnit.MILLISECONDS.sleep(88); s.stop(); System.out.println(s.getTotalTimeMillis()); System.out.println(s.getTotalTimeSeconds()); } }
第二種使用方法(org.apache.commons.lang3.time.StopWatch): spring
package testService; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.time.StopWatch; public class Test { public static void main(String[] args) throws InterruptedException { testSpringStopwatch(); } private static void testSpringStopwatch() throws InterruptedException { StopWatch s = new StopWatch(); s.start(); TimeUnit.MILLISECONDS.sleep(88); s.stop(); System.out.println("納秒:"+s.getNanoTime()); System.out.println("毫秒:"+s.getTime()); } }
第三種使用方法(guava):apache
package testService; import java.util.concurrent.TimeUnit; import com.google.common.base.Stopwatch; public class Test { public static void main(String[] args) throws InterruptedException { testSpringStopwatch(); } private static void testSpringStopwatch() throws InterruptedException { Stopwatch stopwatch = Stopwatch.createStarted(); // Stopwatch stopwatch = Stopwatch.createUnstarted().start(); 或者用這種,不推薦用new Stopwatch(); TimeUnit.MILLISECONDS.sleep(88); long nanos = stopwatch.elapsed(TimeUnit.NANOSECONDS); long mills = stopwatch.elapsed(TimeUnit.MILLISECONDS); long seconds = stopwatch.elapsed(TimeUnit.SECONDS); System.out.println(mills); System.out.println(nanos); System.out.println(seconds); } }
讀取Stopwatch結果:
在結束計時後下一步就是讀取計時結果了。Stopwatch類提供瞭如下屬性:google
應當根據計時任務的狀況選擇其中的一個屬性。在咱們的示例程序中,Elapsed屬性提供了須要的精確度,用它來輸出通過的微秒數
。這也是TimeSpan的最高精確度了。spa