【发布时间】:2019-04-30 00:52:02
【问题描述】:
我有以下 C 代码。在我的机器上,我在 13 秒左右计时。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
clock_t begin = clock();
double d = 0;
for (int i = 0; i < 1e9; i++) {
d = 1 + rand() * 5 > 10 ? 4 : rand();
}
clock_t end = clock();
double time_spent = (double) (end - begin) / CLOCKS_PER_SEC;
printf("%f", time_spent);
return EXIT_SUCCESS;
}
但是这个 numpy 操作,我的时钟只有几分之一秒!
a = np.random.randn(1000, 1000)
b = np.random.randn(1000, 1000)
c = a.dot(b)
考虑到他们正在做相同数量的工作(1e9 次操作),这怎么可能? numpy 是并行化的吗?
【问题讨论】:
-
你在什么操作系统上运行?如果您使用的是 Linux,请在运行 numpy 操作的同时从命令行运行
top命令,并直观地检查正在使用的内核数。虽然我怀疑 numpy 在没有你明确告诉它这样做的情况下不会使用并行性。 -
您的 C 程序实际上在中间有一个
if- 这通常会使 CPU 停顿。 -
您正在执行非常不同的操作。一方面,您的 Python 正在生成 2e6 伪随机数;您的 C 代码,至少 1e9 除了两个代码都在做的乘法和求和。你宁愿举起一千张纸还是一千颗炮弹?为什么?不一样吗,千千万万?
-
尝试做 np.random.randn(31623, 31623)
-
在 c 中,由于循环中的条件,您正在执行超过 10^9 rand() 操作。
标签: python c performance numpy time