全路徑名:
com.google.common.base
** Stopwatch**
聲明
@Beta
@GwtCompatible(emulated=true) public final class Stopwatch extends Object
簡介
用來計(jì)算經(jīng)過的時(shí)間(精確到納秒)芽世。
這個(gè)類比調(diào)用System.nanoTime()優(yōu)勢在于:
- 性能
- 表現(xiàn)形式更豐富
構(gòu)造器
- Stopwatch()
創(chuàng)建(但不啟動(dòng))一個(gè)新的stopwatch對象,用的是System.nanoTime()作為時(shí)間資源具温。 - Stopwatch(Tick tick)
創(chuàng)建(但不啟動(dòng))一個(gè)新的stopwatch對象,用的是特定的時(shí)間資源。
方法
isRunning
public boolean isRunning()
如果start方法被調(diào)用。stop方法還沒有調(diào)用展姐。返回真。
start
@CanIgnoreReturnValue
public Stopwatch start()
啟動(dòng)stopwatch剖毯。
stop
@CanIgnoreReturnValue
public Stopwatch stop()
停止stopwatch,讀取的話將會(huì)返回經(jīng)歷過的時(shí)間教馆。
reset
@CanIgnoreReturnValue
public Stopwatch reset()
把stopwatch經(jīng)過的時(shí)間設(shè)置為零逊谋,狀態(tài)設(shè)置為停止。
elapsed
public long elapsed(TimeUnit desiredUnit)
用特定的格式返回這個(gè)stopwatch經(jīng)過的時(shí)間土铺。
toString
@Override
public String toString()
返回字符串形式的elapsed time胶滋。
例子
public class StopWatchTest {
public static void main(String[] args) throws Exception{
// 創(chuàng)建stopwatch并開始計(jì)時(shí)
Stopwatch stopwatch = Stopwatch.createStarted();
Thread.sleep(1980);
// 以秒打印從計(jì)時(shí)開始至現(xiàn)在的所用時(shí)間,向下取整
System.out.println(stopwatch.elapsed(TimeUnit.SECONDS)); // 1
// 停止計(jì)時(shí)
stopwatch.stop();
System.out.println(stopwatch.elapsed(TimeUnit.SECONDS)); // 1
// 再次計(jì)時(shí)
stopwatch.start();
Thread.sleep(100);
System.out.println(stopwatch.elapsed(TimeUnit.SECONDS)); // 2
// 重置并開始
stopwatch.reset().start();
Thread.sleep(1030);
// 檢查是否運(yùn)行
System.out.println(stopwatch.isRunning()); // true
long millis = stopwatch.elapsed(TimeUnit.MILLISECONDS); // 1031
System.out.println(millis);
// 打印
System.out.println(stopwatch.toString()); // 1.03 s
}
}