在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:

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

5、使用Spring 框架提供的StopWatch

代码如下:

import org.springframework.util.StopWatch;

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

//some code

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