Numpy比纯C快吗?

Tru*_*ell -7 c python performance time numpy

我有以下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;
}
Run Code Online (Sandbox Code Playgroud)

但是这个numpy操作,我只需要几分之一秒!

a = np.random.randn(1000, 1000)
b = np.random.randn(1000, 1000)
c = a.dot(b)
Run Code Online (Sandbox Code Playgroud)

这是如何可能的,因为他们正在做相同数量(1e9操作)的工作?numpy并行化?

hir*_*ist 6

你的pragrams不是一样的.您的C程序rand 至少会 调用10^9一次.此外,你有你的randoms条件.

numpy只创建2个1000x1000数组2x10^6.随机值没有条件.dot产品然后添加O(n^3)操作(和数组创建),但是非常优化.

因此,您基本上将顺序rand调用C与更少的randn调用以及dotpython中的优化操作()进行比较.

为了获得有效的基准,您应该有2个程序执行完全相同的操作.

  • 你还在比较*非常*不同的操作.`~10 ^ 9``rand()`调用vs`10 ^ 6``nrand()`调用加乘法/数组创建.对于真正的基准测试,您应该确保您的程序完全相同. (4认同)
  • 矩阵点积乘以O(n ^ 3),即1e9. (3认同)
  • @Arthur-1`random`不是系统调用. (2认同)