覚えたら書く

IT関係のデベロッパとして日々覚えたことを書き残したいです。twitter: @yyoshikaw

いろんな現在日時取得のベンチマーク

Javaで現在日時(現在日)を取得するAPIがいくつかありますが、それらのベンチマークを取得してみました。

比較したAPI(クラス)は以下の通りです

  • new java.util.Date
  • java.util.Calendar#getInstance
  • java.time.LocalDate#now
  • java.time.LocalDateTime#now
  • java.time.LocalTime#now
  • java.lang.System#currentTimeMillis
  • java.lang.System#nanoTime

当然ですが、現在日時(現在日)といっても、APIによって取得できる情報量や情報の精度が違います。
そのため、単純には早い遅いを言うことはできません。
が、一応目安として性能にどんな差があるのかを見てもらえればと思います。

JMHでの測定用のコードは以下です

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

public class CurrentDateBenchmark {

    @Benchmark
    public void java_util_Date() {
        java.util.Date now = new Date();
    }

    @Benchmark
    public void java_util_Calendar() {
        java.util.Calendar now = Calendar.getInstance();
    }

    @Benchmark
    public void java_time_LocalDateTime() {
        LocalDateTime now = LocalDateTime.now();
    }

    @Benchmark
    public void java_time_LocalDate() {
        LocalDate now = LocalDate.now();
    }

    @Benchmark
    public void java_time_LocalTime() {
        LocalTime now = LocalTime.now();
    }

    @Benchmark
    public void system_currentTimeMillis() {
        long now = System.currentTimeMillis();
    }

    @Benchmark
    public void system_nanoTime() {
        long now = System.nanoTime();
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(CurrentDateBenchmark.class.getSimpleName())
                .warmupIterations(15)
                .forks(1)
                .mode(Mode.Throughput)
                .build();
        new Runner(opt).run();
    }

}

結果:

# Run complete. Total time: 00:04:15

Benchmark                                       Mode  Cnt         Score        Error  Units
CurrentDateBenchmark.java_time_LocalDate       thrpt   20   4185394.021 ±  97163.865  ops/s
CurrentDateBenchmark.java_time_LocalDateTime   thrpt   20   3366750.698 ± 323608.926  ops/s
CurrentDateBenchmark.java_time_LocalTime       thrpt   20   4187783.653 ± 167584.184  ops/s
CurrentDateBenchmark.java_util_Calendar        thrpt   20   1817548.984 ±  51785.421  ops/s
CurrentDateBenchmark.java_util_Date            thrpt   20  43525241.528 ± 427697.286  ops/s
CurrentDateBenchmark.system_currentTimeMillis  thrpt   20  43842100.262 ± 176389.472  ops/s
CurrentDateBenchmark.system_nanoTime           thrpt   20  21670490.836 ± 117075.827  ops/s

取得した値をその後どう扱うのか(例えばフォーマットするとか)等によっても各APIの差があると思いますが、 それでもjava.util.Calendarは何だか苦しい結果になっています。



関連エントリ