【问题标题】:What is the reason that python is so much slower than C in this instance?在这种情况下,python 比 C 慢得多的原因是什么?
【发布时间】:2016-07-19 00:14:38
【问题描述】:

我正在解决项目 euler 的一些问题,我为问题 10 编写了相同的函数...

让我吃惊的是,C 解决方案运行时间约为 4 秒,而 python 解决方案运行时间约为 283 秒。我正在努力向自己解释为什么 C 实现比 python 实现快得多,到底发生了什么?

C:

#include <stdio.h>
#include <time.h>
#include <math.h>

int is_prime(int num)
{
    int sqrtDiv = lround(sqrt(num));
    while (sqrtDiv > 1) {
        if (num % sqrtDiv == 0) {
            return(0);
        } else {
            sqrtDiv--;
        }
    }
    return(1);
}

int main () 
{
    clock_t start = clock();

    long sum = 0;
    for ( int i = 2; i < 2000000; i++ ) {
        if (is_prime(i)) {
            sum += i;
        }
    }
    printf("Sum of primes below 2,000,000 is: %ld\n", sum);

    clock_t end = clock();
    double time_elapsed_in_seconds = (end - start)/(double)CLOCKS_PER_SEC;
    printf("Finished in %f seconds.\n", time_elapsed_in_seconds);   
}

Python:

from math import sqrt
import time


def is_prime(num):
    div = round(sqrt(num))
    while div > 1:
        if num % div == 0:
            return False
        div -= 1
    return True

start_time = time.clock()

tsum = 0
for i in range(2, 2000000):
    if is_prime(i):
        tsum += i

print tsum
print('finished in:', time.clock() - start_time, 'seconds')

【问题讨论】:

  • 如果您使用的是 Python 2.7,range(2, 2000000) 实际上会构建一个包含大约 2000000 个整数的内存列表。您没有在 C 中执行相同的等效操作。请尝试使用 xrange(),或切换到 Python 3,其中 range() 是一个惰性迭代器。
  • 静态类型声明,并可能使用内存效率低的迭代器与 python 中的生成器
  • div 在你的 python 代码中是浮点数,但 sqrtDiv 在你的 C 代码中是 int。
  • round(sqrt(num)) -&gt; int(sqrt(num) + 1) 速度提高了 2.5 倍。在这种情况下,我认为 range 与 xrange 没有任何区别。

标签: python c


【解决方案1】:

在这种情况下,慢的是 CPython(实现),不一定是 Python。 CPython 需要解释几乎总是比编译的 C 代码慢的字节码。它只是比等效的 C 代码做更多的工作。例如,理论上每次调用sqrt 都需要查找该函数,而不仅仅是调用已知地址。

如果您想从 Python 获得相当的速度,您可以使用类型注释源代码并使用 Cython 编译,或者尝试使用 Pypy 运行以获得一些 JIT 性能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    相关资源
    最近更新 更多