Created
July 12, 2015 10:19
-
-
Save Yuiki/672f493af193806ec0dd to your computer and use it in GitHub Desktop.
ArrayList処理と配列処理の実行時間の比較。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Main { | |
private final int quantity = 1000000; | |
// frequencyの値を増やすほど精度が増す。 | |
private final int frequency = 10; | |
// コンストラクタで要素数指定。 | |
private final List<Integer> list = new ArrayList<>(quantity); | |
private final int[] array = new int[quantity]; | |
public static void main(String[] args) { | |
Main main = new Main(); | |
List<Long> arrayMeanValue = new ArrayList<>(); | |
List<Long> arrayListMeanValue = new ArrayList<>(); | |
System.out.println("要素数" + main.quantity + "で処理を開始します。"); | |
for (int i = 0; i < main.frequency; i++) { | |
System.out.println("配列処理(" + i + 1 + "回目)を開始します。"); | |
long executionTimeArray = main.measureTime(main::useArray, main.quantity); | |
System.out.println("終了しました。"); | |
arrayMeanValue.add(executionTimeArray); | |
System.out.println("ArrayList処理(" + i + 1 + "回目)を開始します。"); | |
long executionTimeList = main.measureTime(main::useArrayList, main.quantity); | |
System.out.println("終了しました。"); | |
arrayListMeanValue.add(executionTimeList); | |
} | |
long arrayMeanValueAve = main.calcAverage(arrayMeanValue); | |
long arrayListMeanValueAve = main.calcAverage(arrayListMeanValue); | |
System.out.println("配列処理の実行平均時間:" + arrayMeanValueAve/ 1000000 + "ms"); | |
System.out.println("ArrayList処理の実行時間:" + arrayListMeanValueAve / 1000000 + "ms"); | |
System.out.println("配列処理のほうが" + main.compareValue(arrayMeanValueAve, arrayListMeanValueAve) / 1000000 + "ms速いです。"); | |
} | |
private void useArray(int quantity) { | |
for (int i = 0; i < quantity; i++) { | |
array[i] = i; | |
} | |
Arrays.stream(array).forEach(System.out::println); | |
Arrays.fill(array, 0); | |
} | |
private void useArrayList(int quantity) { | |
for (int i = 0; i < quantity; i++) { | |
list.add(i); | |
} | |
list.stream().forEach(System.out::println); | |
list.clear(); | |
} | |
private long calcAverage(List<Long> list) { | |
long sum = 0; | |
for (long value : list) { | |
sum += value; | |
} | |
return sum / list.size(); | |
} | |
private long compareValue(long a, long b) { | |
return a - b; | |
} | |
private <T> long measureTime(Consumer<T> proc, T arg) { | |
long start = System.nanoTime(); | |
proc.accept(arg); | |
return System.nanoTime() - start; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment