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>

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());