62,621
社区成员
发帖
与我相关
我的任务
分享 /**
* 获得耗时
* @return
*/
public long spendTime() {
if(end == 0L) {
stop();
}
return (end - start);
}
/**
* 启动计时器
*/
public void start() {
end = 0L;
start = getCurrentTime();
}public class Test {
public static void main(String[] args) {
Clock clock = Clock.getNanoSecondClock();
clock.start();
for(int i = 0; i < 10000; i++);
clock.stop();
System.out.println(clock.spendTime());
}
}/**
* 用于测量代码执行的计时器
*/
public abstract class Clock {
private long start;
private long end;
private Clock() { }
private final static Clock MILLIS_SECOND_CLOCK = new Clock() {
protected long getCurrentTime() {
return System.currentTimeMillis();
}
};
private final static Clock NANO_SECOND_CLOCK = new Clock() {
protected long getCurrentTime() {
return System.nanoTime();
}
};
/**
* 获得毫秒级别的计时器
* @return
*/
public static Clock getMillisSecondClock() {
return MILLIS_SECOND_CLOCK;
}
/**
* 获得纳秒级别的计时器
* @return
*/
public static Clock getNanoSecondClock() {
return NANO_SECOND_CLOCK;
}
/**
* 获得耗时
* @return
*/
public long spendTime() {
if(end == 0L) {
stop();
}
long spend = end - start;
start = end = 0L;
return spend;
}
/**
* 启动计时器
*/
public void start() {
start = getCurrentTime();
}
/**
* 停止计时器
*/
public void stop() {
end = getCurrentTime();
}
/**
* 获得当前计时器的时间
* @return
*/
protected abstract long getCurrentTime();
}
public class Test2 {
public static void main(String[] args){
String str="";
long startTime=System.currentTimeMillis();//开始计时
//这里得到的时间是一个long型的毫秒数,具体是怎么样一个毫秒数去查API中的System的这个方法
for(int i=0;i<1000;i++){
str=str+1;
}
long endTime=System.currentTimeMillis();//结束获取结束时的时间
long runTime=endTime-startTime;//两个时间只差就是运行时间
System.out.print("程序运行时间是:"+runTime+"毫秒");
}
}