简体   繁体   English

在这种情况下,python比C慢得多的原因是什么?

[英]What is the reason that python is so much slower than C in this instance?

I was solving some problems on project euler and I wrote identical functions for problem 10... 我在项目euler上解决了一些问题,我为问题10编写了相同的函数...

The thing that amazes me is that the C solution runs in about 4 seconds while the python solution takes about 283 seconds. 令我惊讶的是C解决方案在大约4秒内运行,而python解决方案大约需要283秒。 I am struggling to explain to myself why the C implementation is so much faster than the python implementation, what is actually happening to make it so? 我正在努力向自己解释为什么C实现比python实现快得多,实际发生了什么呢?

C: 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')

It's CPython (the implementation) that's slow in this case, not Python necessarily. 这是CPython(实现)在这种情况下很慢,而不是Python必然。 CPython needs to interpret the bytecode which will almost always be slower than compiled C code. CPython需要解释字节码,它几乎总是比编译的C代码慢。 It simply does more work than the equivalent C code. 它只是比同等的C代码做更多的工作。 In theory each call to sqrt for example requires looking up that function, rather than just a call to a known address. 理论上,每次调用sqrt需要查找该函数,而不仅仅是调用已知地址。

If you want comparable speed from Python, you could either annotate the source with types and compile with Cython, or try running with Pypy for some JIT performance. 如果你想要与Python相媲美的速度,你可以使用类型注释源代码并使用Cython进行编译,或者尝试使用Pypy运行以获得一些JIT性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM