System.currentTimeMillis()

1
2
3
4
5
6
long start = System.currentTimeMillis();

// 业务代码

long finish = System.currentTimeMillis();
long timeElapsed = finish - start;

System.nanoTime()

1
2
3
4
5
6
long start = System.nanoTime();

// 业务代码

long finish = System.nanoTime();
long timeElapsed = finish - start;

java8 Instant.now()

1
2
3
4
5
6
Instant start = Instant.now();

// 业务代码

Instant finish = Instant.now();
long timeElapsed = Duration.between(start, finish).toMillis();

apache.commons StopWatch

  1. pom.xml

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    import org.apache.commons.lang3.time.StopWatch;

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

    // 业务代码

    watch.stop();
    System.out.println("Time Elapsed: " + watch.getTime());

Spring StopWatch

1
2
3
4
5
6
7
8
9
import org.springframework.util.StopWatch;

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

// 业务代码

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