文章目录
多种获取代码运行时长的方法,
System.currentTimeMillis
通过java内置的方法System.currentTimeMillis()获取毫秒时间戳,然后通过代码结束时间减去代码开始时间,获取运行时长
@Test
public void test2() throws InterruptedException {
long startLong = System.currentTimeMillis();
Thread.sleep(1000);
long endLong = System.currentTimeMillis();
System.out.println(endLong-startLong);
}
System.nanoTime
通过java内置的方法System.nanoTime()获取纳秒时间戳,然后通过代码结束时间减去代码开始时间,获取运行时长.
@Test
public void test2() throws InterruptedException {
// 开始时间
long start = System.nanoTime();
// 执行时间(1s)
Thread.sleep(1000);
// 结束时间
long end = System.nanoTime();
// 计算执行时间
System.out.printf("执行时长:%d 纳秒.", (end - start));
}
new Date
这个是先通过Date获取时间,然后通过Date.getTime()获取时间戳,然后通过代码结束时间减去代码开始时间,获取运行时长
@Test
public void test2() throws InterruptedException {
// 开始时间
Date start = new Date();
// 执行时间(1s)
Thread.sleep(1000);
// 结束时间
Date end = new Date();
// 统计执行时间(毫秒)
System.out.printf("执行时长:%d 毫秒." , (end.getTime() - start.getTime()));
}
Spring StopWatch
spring-framework提供了的StopWatch类,提供了丰富的方法,可以获取到单个、多个等运行时间
简单的运行时间
@Test
public void test3() throws InterruptedException {
StopWatch sw = new StopWatch();
//开始监控
sw.start();
Thread.sleep(1000);
//停止监控
sw.stop();
//获取总耗时
System.out.println(sw.getTotalTimeMillis());
}
多个运行时间
@Test
public void test2() throws InterruptedException {
StopWatch sw = new StopWatch();
sw.start("A");
Thread.sleep(500);
sw.stop();
sw.start("B");
Thread.sleep(300);
sw.stop();
sw.start("C");
Thread.sleep(200);
sw.stop();
//表格形式输出各项任务耗时
System.out.println(sw.prettyPrint());
//获取所有任务总耗时
System.out.println(sw.getTotalTimeMillis());
}
StopWatch. TaskInfo
获取最后一个任务的信息,返回一个StopWatch. TaskInfo静态内部类,有各种方法
@Test
public void test3() throws InterruptedException {
StopWatch sw = new StopWatch();
//开始监控
sw.start();
Thread.sleep(1000);
//停止监控
sw.stop();
//获取总耗时
System.out.println(sw.getTotalTimeMillis());
//获取最后一个任务的信息,返回一个StopWatch. TaskInfo静态内部类,有各种方法
System.out.println(sw.lastTaskInfo().getTimeSeconds());
}
Spring StopWatch其它API
- getTotalTimeSeconds() 获取总耗时秒,同时也有获取毫秒的方法
- prettyPrint() 优雅的格式打印结果,表格形式
- shortSummary() 返回简短的总耗时描述
- getTaskCount() 返回统计时间任务的数量
- getLastTaskInfo().getTaskName() 返回最后一个任务TaskInfo对象的名称
- 更多API:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/StopWatch.html
commons-lang3 StopWatch
统计单个的执行时长,可以获取以秒、毫秒、纳秒为单位的执行时长
- 引入依赖
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
- 测试
@Test
public void test3() throws InterruptedException {
StopWatch stopWatch = new StopWatch();
// 开始时间
stopWatch.start();
// 执行时间(1s)
Thread.sleep(1000);
// 结束时间
stopWatch.stop();
// 统计执行时间(秒)
System.out.println("执行时长:" + stopWatch.getTime(TimeUnit.SECONDS) + " 秒.");
// 统计执行时间(毫秒)
System.out.println("执行时长:" + stopWatch.getTime(TimeUnit.MILLISECONDS) + " 毫秒.");
// 统计执行时间(纳秒)
System.out.println("执行时长:" + stopWatch.getTime(TimeUnit.NANOSECONDS) + " 纳秒.");
}