StopWatch 類提供碼錶功能,支援啟動、停止、重置、分段計時,並能以「時:分:秒:毫秒」格式輸出經過時間,適合除錯與效能測試場景。
start():記錄開始時間(System.currentTimeMillis())stop():記錄結束時間reset():重置計時器split() / unsplit():分段計時控制getTime():取得經過毫秒數getTimeString():取得格式化字串(如 1h:30m:45s:123ms)toString():直接回傳格式化時間字串package com.generationJava.test;
public class StopWatch {
static public int AN_HOUR = 60 * 60 * 1000;
static public int A_MINUTE = 60 * 1000;
private long startTime = -1;
private long stopTime = -1;
public void start() {
this.startTime = System.currentTimeMillis();
}
public void stop() {
this.stopTime = System.currentTimeMillis();
}
public void reset() {
this.startTime = -1;
this.stopTime = -1;
}
public void split() {
this.stopTime = System.currentTimeMillis();
}
public void unsplit() {
this.stopTime = -1;
}
public long getTime() {
if (stopTime != -1) {
return (System.currentTimeMillis() - this.startTime);
} else {
return this.stopTime - this.startTime;
}
}
public String toString() {
return getTimeString();
}
public String getTimeString() {
int hours, minutes, seconds, milliseconds;
long time = getTime();
hours = (int) (time / AN_HOUR);
time -= hours * AN_HOUR;
minutes = (int) (time / A_MINUTE);
time -= minutes * A_MINUTE;
seconds = (int) (time / 1000);
time -= seconds * 1000;
milliseconds = (int) time;
return hours + "h:" + minutes + "m:" + seconds + "s:" + milliseconds + "ms";
}
}
StopWatch sw = new StopWatch();
sw.start();
// 執行待測程式碼
sw.stop();
System.out.println("耗時:" + sw.getTimeString());
輸出範例:耗時:0h:0m:3s:245ms