StopWatch的用法

时间:2023-03-09 17:13:44
StopWatch的用法

在学习spring的时候,看到关于统计时间的类,比较好奇,就记录下来,以便以后用到可以直接使用
org.springframework.util.StopWatch

StopWatch该类在统计时间的时候,必须得前一个对象关闭才能创建新的StopWatch,并且在统计完成后,只需要将其输出,就可以像报表一样,显示统计的时间

在开发中,常用于统计时间的是 使用 System.currentTimeMillis();进行统计,并且当执行完毕后,

还需要相减,才能得到最终时间值,不过,stopWatch差不多也是类似功能吧

	public static void main(String[] args) throws InterruptedException {
StopWatch sw = new StopWatch();
sw.start("读取文件");
Thread.sleep(1000);
sw.stop();
sw.start("文件删除");
Thread.sleep(100);
sw.stop();
sw.start("文件拷贝");
Thread.sleep(10);
sw.stop();
System.out.println(sw.prettyPrint()); long stime =System.currentTimeMillis();
Thread.sleep(1000);
long etime =System.currentTimeMillis();
System.out.println("执行时间:"+(etime-stime));
}

执行结果:
StopWatch '': running time (millis) = 1110

-----------------------------------------

ms % Task name

-----------------------------------------

01000 090% 读取文件

00100 009% 文件删除

00010 001% 文件拷贝

执行时间:1000

查看其内部源码,我们可以看到,该类封装了System.currentTimeMillis();在同一个stopWatch对象中,将每次stop都存放在linklist中,在统计的时候,再取出输出

	private final List<TaskInfo> taskList = new LinkedList<TaskInfo>();

	public void start(String taskName) throws IllegalStateException {
if (this.running) {
throw new IllegalStateException("Can't start StopWatch: it's already running");
}
this.startTimeMillis = System.currentTimeMillis();
this.running = true;
this.currentTaskName = taskName;
} /**
* Stop the current task. The results are undefined if timing
* methods are called without invoking at least one pair
* {@link #start()} / {@link #stop()} methods.
* @see #start()
*/
public void stop() throws IllegalStateException {
if (!this.running) {
throw new IllegalStateException("Can't stop StopWatch: it's not running");
}
long lastTime = System.currentTimeMillis() - this.startTimeMillis;
this.totalTimeMillis += lastTime;
this.lastTaskInfo = new TaskInfo(this.currentTaskName, lastTime);
if (this.keepTaskList) {
this.taskList.add(lastTaskInfo);
}
++this.taskCount;
this.running = false;
this.currentTaskName = null;
} /**
* Return an array of the data for tasks performed.
*/
public TaskInfo[] getTaskInfo() {
if (!this.keepTaskList) {
throw new UnsupportedOperationException("Task info is not being kept!");
}
return this.taskList.toArray(new TaskInfo[this.taskList.size()]);
}