一、代码
public class Timer {
private double begin = 0;
public Timer(){
resetBegin();
}
public void resetBegin(){
begin = System.currentTimeMillis(); // 程序开始时间,调用系统的当前时间
}
/**
* 打印时间差,从begin开始
*/
public void printRunTime(){
// 你要运行的程序
double end = System.currentTimeMillis(); // 程序结束时间,调用系统当前时间
//System.out.println("end="+end);
double time = end - begin;// 程序的运行时间
begin = end;
System.out.println("运行时间为:"+time + "毫秒");
}
}
二、说明
实例化类时,获得系统时间(毫秒),调用一次printRunTime()输出一次时间差,同时将开始时间设置为当前时间
使用方法为
Timer timer = new Timer();
/* 待统计代码/
timer.printRunTime();