⭐⭐⭐ Spring Boot 项目实战 ⭐⭐⭐ Spring Cloud 项目实战
《Dubbo 实现原理与源码解析 —— 精品合集》 《Netty 实现原理与源码解析 —— 精品合集》
《Spring 实现原理与源码解析 —— 精品合集》 《MyBatis 实现原理与源码解析 —— 精品合集》
《Spring MVC 实现原理与源码解析 —— 精品合集》 《数据库实体设计合集》
《Spring Boot 实现原理与源码解析 —— 精品合集》 《Java 面试题 + Java 学习指南》

摘要: 原创出处 blog.csdn.net/inrgihc 「inrgihc」欢迎转载,保留摘要,谢谢!



在java开发过程中,常常会用一些方法来计算一段代码的耗时,那么java中计算耗时的方法有哪些,这里整理总结如下:

1、使用System.currentTimeMillis()函数

代码如下:

long start = System.currentTimeMillis();
// some code
long finish = System.currentTimeMillis();
long timeElapsed = finish - start;

2、使用System.nanoTime()函数

代码如下:

long start = System.nanoTime();
// some code
long finish = System.nanoTime();
long timeElapsed = finish - start;

3、在java8中使用Instant.now()函数

代码如下:

Instant start = Instant.now();
// some code
Instant finish = Instant.now();
long timeElapsed = Duration.between(start, finish).toMillis();

4、使用apache.commons提供的StopWatch

首先,在pom.xml中添加如下依赖:

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>

5、使用Spring 框架提供的StopWatch

代码如下:

import org.springframework.util.StopWatch;

StopWatch watch = new StopWatch();
watch.start("watcher");

//some code

watch.stop();
System.out.println(watch.prettyPrint());