当在日常开发中需要测试程序运行时间,又不想使用JMH测试框架,因此本文列举常用的六种方法
示例1:System.currentTimeMillis(java内置方法)
// 开始时间
long stime = System.currentTimeMillis();
// 执行时间(睡眠1s)
Thread.sleep(1000);
// 结束时间
long etime = System.currentTimeMillis();
// 计算执行时间
System.out.printf("执行时长:%d 毫秒.", (etime - stime));//执行时长:1000 毫秒.
示例2:System.nanoTime(java内置方法)
// 开始时间
long stime = System.nanoTime();
// 执行时间(1s)
Thread.sleep(1000);
// 结束时间
long etime = System.nanoTime();
// 计算执行时间
System.out.printf("执行时长:%d 纳秒.", (etime - stime));//执行时长:1003340200 纳秒.
示例3:Date()(java内置方法)
// 开始时间
Date sdate = new Date();
// 执行时间(1s)
Thread.sleep(1000);
// 结束时间
Date edate = new Date();
// 统计执行时间(毫秒)
System.out.printf("执行时长:%d 毫秒." , (edate.getTime() - sdate.getTime()));//执行时长:1000 毫秒.
示例4:StopWatch()(需在spring或springboot项目中使用,不需要配置依赖)
StopWatch stopWatch = new StopWatch();
// 开始时间
stopWatch.start();
// 执行时间(1s)
Thread.sleep(1000);
// 结束时间
stopWatch.stop();
// 统计执行时间(秒)%n 为换行
System.out.printf("执行时长:%f 秒.%n", stopWatch.getTotalTimeSeconds());
// 统计执行时间(毫秒)
System.out.printf("执行时长:%d 毫秒.%n", stopWatch.getTotalTimeMillis());
// 统计执行时间(纳秒)
System.out.printf("执行时长:%d 纳秒.%n", stopWatch.getTotalTimeNanos());
/*
执行时长:0.996446 秒.
执行时长:996 毫秒.
执行时长:996445900 纳秒.
*/
示例5:commons-lang3(需要配置依赖)
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
StopWatch stopWatch = new StopWatch();
// 开始时间
stopWatch.start();
// 执行时间(1s)
Thread.sleep(1000);
// 结束时间
stopWatch.stop();
// 统计执行时间(秒)
System.out.println("执行时长:" + stopWatch.getTotalTimeSeconds() + " 秒.");
// 统计执行时间(毫秒)
System.out.println("执行时长:" + stopWatch.getTotalTimeMillis() + " 毫秒.");
// 统计执行时间(纳秒)
System.out.println("执行时长:" + stopWatch.getTotalTimeNanos() + " 纳秒.");
/*
执行时长:1.0000573 秒.
执行时长:1000 毫秒.
执行时长:1000057300 纳秒.
*/
示例6:com.google.guava(需要添加依赖)
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.0-jre</version>
</dependency>
// 创建并启动计时器
Stopwatch stopwatch = Stopwatch.createStarted();
// 执行时间(1s)
Thread.sleep(1000);
// 停止计时器
stopwatch.stop();
// 执行时间(单位:秒)
System.out.printf("执行时长:%d 秒. %n", stopwatch.elapsed().getSeconds()); // %n 为换行
// 执行时间(单位:毫秒)
System.out.printf("执行时长:%d 豪秒.", stopwatch.elapsed(TimeUnit.MILLISECONDS));
/*
执行时长:0 秒.
执行时长:996 豪秒.
*/