1、使用System.currentTimeMillis()函数
代码如下:
long start = System.currentTimeMillis();
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());
转载于公众号 java基基
本文介绍了Java中几种常见的性能监控和测量技术,包括使用System.currentTimeMillis()、System.nanoTime()、Instant.now()函数以及Apache Commons Lang的StopWatch和Spring框架的StopWatch。这些工具可以帮助开发者精确地计算代码执行时间,从而优化程序性能。
12万+

被折叠的 条评论
为什么被折叠?



