在本例中,python比C慢得多的原因是什么?

2024-09-28 01:59:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我在解决欧拉项目的一些问题,我为问题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')

Tags: indivreturnifincludetimeissqrt
1条回答
网友
1楼 · 发布于 2024-09-28 01:59:56

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

如果希望Python的速度与之相当,可以使用类型对源代码进行注释并使用Cython进行编译,或者尝试使用Pypy运行以获得一些JIT性能。你知道吗

相关问题 更多 >

    热门问题