Java统计代码的执行时间

当在日常开发中需要测试程序运行时间,又不想使用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 豪秒.
*/
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丶橙七

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值