第一种方式:System.currentTimeMillis()
@Test
public void test1() throws Exception{
long start = System.currentTimeMillis();
Thread.sleep(5);
long end = System.currentTimeMillis();
System.out.println(end -start);
}
第二种方式: System.nanoTime()
@Test
public void test2() throws Exception{
long start = System.nanoTime();
Thread.sleep(5);
long end = System.nanoTime();
//注意单位:1秒等于100万纳秒
System.out.println(end -start);
}
第三种方式:new Date()
@Test
public void test3() throws Exception{
Date start = new Date();
Thread.sleep(5);
Date end = new Date();
System.out.println(end.getTime() -start.getTime());
}
第四种方式:spring util 里面提供的StopWatch
@Test
public void test4() throws Exception{
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Thread.sleep(5);
stopWatch.stop();
System.out.println(stopWatch.getTotalTimeMillis());
}
StopWatch 其实不仅仅是封了一下耗时统计,还有如下作用:
void start(“任务名称”):开始一个任务名称的计时
void stop():停止当前任务的计时
boolean isRunning():是否正在计时某任务
long getTotalTimeMillis():所有任务的总体执行时间(毫秒单位)
double getTotalTimeSeconds():所有任务的总时间(以秒为单位)
long getLastTaskTimeMillis():上一个任务的耗时(毫秒单位)
int getTaskCount():定时任务的数量
String prettyPrint():优美地打印所有任务的详细耗时情况
StopWatch.TaskInfo[] getTaskInfo():包含任务名称和任务耗时的实体类数组