Several ways to realize time-consuming in JAVA

1. Use the System.currentTimeMillis() function

code show as below:

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

2. Use the System.nanoTime() function

code show as below:

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

3. Use the Instant.now() function in java8

code show as below:

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

4. Use StopWatch provided by apache.commons

First, add the following dependencies to pom.xml:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.7</version>
</dependency>

5. Use the StopWatch provided by the Spring framework

code show as below:

import org.springframework.util.StopWatch;
 
StopWatch watch = new StopWatch();
watch.start("watcher");
 
//some code
 
watch.stop();
System.out.println(watch.prettyPrint());

Reprinted from the public account java base

Guess you like

Origin blog.csdn.net/lijie0213/article/details/124721767