admin管理员组

文章数量:1794759

Java:计算代码耗时的5种方法

Java:计算代码耗时的5种方法

点击关注公众号,利用碎片时间学习

在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、使用apachemons提供的StopWatch

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

<dependency>     <groupId>org.apachemons</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());

来源:blog.csdn/inrgihc

推荐:

主流Java进阶技术(学习资料分享)

PS:因为公众号平台更改了推送规则,如果不想错过内容,记得读完点一下“在看”,加个“星标”,这样每次新文章推送才会第一时间出现在你的订阅列表里。点“在看”支持我们吧!

本文标签: 种方法代码java