簡易計時器工具類 TimeCounter 使用時方便直接調用,避免重複代碼,保持代碼美觀。直接上代碼:
public class TimeCounter {
private Long time;// 開始時間
private TimeCounter timeCounter;// 當前計時器實例
public TimeCounter() {
timeCounter = this;
}
/**
* 啓動計時器
*/
public TimeCounter start() {
time = System.nanoTime();
return timeCounter;
}
/**
* 計時
*
* @return
*/
public double counts() {
if (time == null) {
throw new RuntimeException("請先啓動計時方法:TimeCounter.start()");
}
return (System.nanoTime() - time) / 1e6d;
}
}
使用方式如下: