NumPy性能小測:與Java性能相當

測試說明

簡單瞭解在Python中 NumPy 與 list 的性能差及與源生Java的性能對比情況。
爲了避免隨機性的影響,每個計算執行10次,取總時間。

測試環境

硬件:ADM R7 3700X, 16GB DDR4 26666
軟件:Windows10 1909 18363.720 | Java11.0.6 | Python3.7.4

測試代碼

Python代碼,使用IPython進行計時。

In [1]: import numpy as np
In [2]: %time arr1 = np.arange(1000_0000)
Wall time: 14 ms
In [3]: %time for _ in range(10): arr2 = arr1 * 10
Wall time: 182 ms
In [4]: %time list1 = list(np.arange(1000_0000))
Wall time: 325 ms
%time for _ in range(10): list2 = [x * 10 for x in list1]
Wall time: 25.6 s

Java代碼

public class Temp20200406 {
	public static void main(String[] args) {
		// creating arr1
		long t = System.currentTimeMillis();
		int[] arr1 = new int[1000_0000];
		long time1 = System.currentTimeMillis() - t;
		System.out.printf("creation arr1: %d ms.\n", time1);

		// creating arr2
		long time2 = 0;
		for (int runningTimes = 0; runningTimes < 10; runningTimes++) {
			t = System.currentTimeMillis();
			int[] arr2 = new int[arr1.length];
			for (int i = 0; i < arr2.length; i++)
				arr2[i] = arr1[i] * 10;
			time2 += System.currentTimeMillis() - t;
		}
		System.out.printf("creation arr2: %d ms.\n", time2);
	}
}

# 測試結果:
creation arr1: 12 ms.
creation arr2: 158 ms.

測試結論

  1. NumPy 與源生 Java 代碼的運算性能很接近(182 ms VS 158 ms);
  2. NumPy 的性能要比 list 強2個量級(182 ms VS 25.6 s,約141倍)。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章