LoginSignup
0
0

More than 5 years have passed since last update.

2つの年月日の間の日数を取得する方法の速さ比較

Last updated at Posted at 2016-10-06

2つの年月日、2000年1月1日と2016年12月31日の日数の差を取得する方法について、以下の2つの速さを比較してみました。

  • Calendarクラスを使う。
  • Durationクラスを使う。(java8)

実行環境は以下の通りです。

  • DELL VOSTRO 1540
  • Windows 10 Pro 32bit
  • Intel Celelron 2.00 GHZ
  • メモリ 2.0GB
  • HDは約300GB

ソースと実行結果

上記の方法を30000回繰り返した結果を出力しました。以下、ソースと実験結果です。

ソース
package test;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.function.LongSupplier;

public class Test {

    // --計測用--
    private void printProcessingTime(LongSupplier f) {
        int count = 30000;
        long start, end;
        start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            f.getAsLong();
        }
        end = System.currentTimeMillis();
        System.out.printf("出力確認:%s, 計測 %3d: ", f.getAsLong(), end - start);
        System.out.println();
    }

    // --計測--
    private static int DIV_FOR_CAL = 1000 * 60 * 60 * 24;
    private static int DIV_FOR_DUR =        60 * 60 * 24;

    public static void main(String[] args) {
        new Test().test();
    }

    private void test() {
        // Calendar
        printProcessingTime(() -> {
            Calendar c1 = Calendar.getInstance();
            c1.set(2000, 0, 1, 0, 0, 0);
            Calendar c2 = Calendar.getInstance();
            c2.set(2016, 11, 31, 0, 0, 0);
            return (c2.getTimeInMillis() - c1.getTimeInMillis())/ DIV_FOR_CAL;
        });

        // Duration
        printProcessingTime(() -> {
            Duration duration = Duration.between(
                    LocalDateTime.of(2000, 1, 1, 0, 0),
                    LocalDateTime.of(2016, 12, 31, 0, 0));
            return duration.getSeconds() / DIV_FOR_DUR;
        });
    }
}
結果
出力確認:6209, 計測 255: 
出力確認:6209, 計測  47: 

Durationの方が速いという結果になりました。

修正履歴

  • @sipadan2003 さんの指摘対応。ソースを修正し、java.util.functionに用意されているインターフェースを使用。
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0