[SOLVED] C++ vs Python execution time mathematical operations

Issue

I have the same code in two different languages: C++ and Python.

C++ code:

#include <iostream>
float m = 16442.34;
float c = 2434.1; 
float t = 0.34;
int n = 3;
float i = 934380.72;
int k = 111;
int ris = 0;
int tot = 0;

int main() {
    while(tot<1000000){
        ris++;
        tot = (ris * (m - c)) - (int(ris/n) *  t * m * n) - (i * int(ris/k));
    }
    std::cout << ris << " steps\n";
}

Python code:

m = 16442.34
c = 2434.1
t = 0.34 
n = 3 
i = 934380.72 
k = 111
ris = 0
tot = 0

while tot<1000000:
    ris+=1
    tot = (ris * (m - c)) - (int(ris/n) *  t * m * n) - (i * int(ris/k))
print(ris, "steps")

Why is there a huge difference in execution time? Is it possible to speed up the Python code? How?

Solution

Python is an interpreted language while C++ gets compiled to machine code. This enables a C++ compiler to produce highly optimized code while the python interpreter "has to think more in order to execute the program".

You could compile the python code (as Samwise said), e.g., with Cython.

Also, you are using 32-bit floats in C++ which yield different floating point errors than the 64-bit (?) numbers of python. Changing the type from float to double at least created the same (apart from minor floating point errors) result for tot and ris. Thanks @Michael Szczesny for pointing towards this bug.

Answered By – J.P.S.

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *