使用StopWatch类来计时 (perf4j-0.9.16.jar 包里的类)

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();

}

/**

* 取得String类型的时间差

* 形式为小时,分钟,秒和毫秒

;*/

public String getTimeString() {

int hours, minutes, seconds,milliseconds;

long time = getTime();

hours = (int) (time / AN_HOUR);

time = time - (hours *AN_HOUR);

minutes = (int) (time /

A_MINUTE);

time = time - (minutes *A_MINUTE);

seconds = (int) (time / 1000);

time = time - (seconds * 1000);

milliseconds = (int) time;

return hours + "h:" +minutes + "m:"_

+ seconds + "s:" + milliseconds +

} 

与大块的代码相比,它是非常简单的。但是它可重用而毫不复杂。因此StopWatch类的使用也是非常简单的:

StopWatch obj = new StopWatch();

obj.start();

try {

Thread.currentThread().sleep(1500);

} catch(InterruptedException ie) {

// ignore

}

obj.stop();

System.out.println(obj); 

我们执行了1500豪秒sleep,完全在预料之中的,StopWatch的报告为:

0h:0m:1s:502ms 

StopWatch不是深奥复杂的科学,但是它确实满足了常见的测量代码行间执行时间的需求

StopWatch stopWatch = new Slf4JStopWatch();  -- 可以new 不同格式的stopWatch
原文地址:https://www.cnblogs.com/wzhanke/p/4765670.html