What is the reason that python in this case is much slower than C?

I solved some problems with the project Euler, and I wrote the same functions for task 10 ...

It amazes me that the C solution works after about 4 seconds, and the python solution takes about 283 seconds. I am struggling to explain to myself why the C implementation is much faster than the python implementation, what is actually happening to make it this way?

WITH

#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')
+4
source share
1 answer

CPython (), , Python . CPython -, , C. , C. sqrt , , , .

Python, , Cython, Pypy JIT.

+2

Source: https://habr.com/ru/post/1648308/


All Articles