转载 

java中计算代码耗时的几种方法_java 计算耗时_inrgihc的博客

分类:    340人阅读    IT小君  2023-09-07 23:14

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

 

1、使用System.currentTimeMillis()函数

代码如下:

  1. long start = System.currentTimeMillis();
  2. // some code
  3. long finish = System.currentTimeMillis();
  4. long timeElapsed = finish - start;

2、使用System.nanoTime()函数

代码如下:

  1. long start = System.nanoTime();
  2. // some code
  3. long finish = System.nanoTime();
  4. long timeElapsed = finish - start;

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

代码如下:

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

4、使用apache.commons提供的StopWatch

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

  1. <dependency>
  2. <groupId>org.apache.commons</groupId>
  3. <artifactId>commons-lang3</artifactId>
  4. <version>3.7</version>
  5. </dependency>

然后使用StopWatch:

  1. StopWatch watch = new StopWatch();
  2. watch.start();
  3. // some code
  4. watch.stop();
  5. System.out.println("Time Elapsed: " + watch.getTime());

5、使用Spring 框架提供的StopWatch

代码如下:

  1. import org.springframework.util.StopWatch;
  2. StopWatch watch = new StopWatch();
  3. watch.start("watcher");
  4. //some code
  5. watch.stop();
  6. System.out.println(watch.prettyPrint());

 

转载于:https://blog.csdn.net/inrgihc/article/details/104344966

支付宝打赏 微信打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者

 工具推荐 更多»