简单了解在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.