JAVA で時間のかかる作業を実現するいくつかの方法

1. System.currentTimeMillis() 関数を使用する

コードは以下のように表示されます:

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

2. System.nanoTime() 関数を使用する

コードは以下のように表示されます:

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

3. java8 で Instant.now() 関数を使用する

コードは以下のように表示されます:

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

4. apache.commons が提供する StopWatch を使用する

まず、次の依存関係を pom.xml に追加します。

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

5. Spring フレームワークが提供する StopWatch を使用する

コードは以下のように表示されます:

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

公開アカウントJavaベースより転載

おすすめ

転載: blog.csdn.net/lijie0213/article/details/124721767