服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

使用stopwatch类来计时


  使用stopwatch类来计时

作者: builder.com

调试器是一个繁重的东西,使用调试器并不总是最有效的方法;有时,你可能想对代码进行一些小的调试和跟踪。一个简单的stopwatch类就是提供了一种好的计时解决方案。

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

}

/**

* 取得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不是深奥复杂的科学,但是它确实满足了常见的测量代码行间执行时间的需求。

扫描关注微信公众号