Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python run a C++ function faster than C++ running its own function via its main() function?

I wrote an extremely brute force function to check if a number is a prime number. The loop goes up to 1,000,000. I compiled that C++ code into a shared library and ran that function with Python, then I ran the same function within C++'s main() function. Why does time show that python did it faster than C++?

My C++ Code (cppcode.cpp):

#include <iostream>
#include <boost/python.hpp>
using namespace boost::python;

bool isPrime(long number) {
    if(number == 2) {
        return true;
    }
    for(int i = 3; i < number; i++) {
        if(number % i == 0) {
            return false;
        }
    }
    return true;
}

void runcpp(void) {
    for(int i = 2; i < 1000000; i++) {
        if(isPrime(i)) {
            std::cout << i << " is a prime number!" << std::endl;
        }
    }
}

BOOST_PYTHON_MODULE(cppcode)
{
    def("runcpp", runcpp);
}

int main() {
    runcpp();
    return 0;
}

My Python Code (main.py):

import cppcode
if __name__ == "__main__":
    cppcode.runcpp()

Shell Output:

$ g++ -Wall -shared -fPIC cppcode.cpp -o cppcode.so -lpython2.7 -lboost_python -I/usr/include/python2.7/
$ g++ -Wall cppcode.cpp -o main -lpython2.7 -lboost_python -I/usr/include/python2.7/
$ (time python main.py >> time.txt) && (time ./main >> time.txt)

real    10m26.519s
user    10m25.042s
sys     0m0.737s

real    10m48.754s
user    10m47.796s
sys     0m0.763s

As you can see from the shell output above, when python ran the C++ "runcpp" function, it ran ~20 seconds faster than when C++'s main() function ran the same "runcpp" function. Does anyone have any idea as to why Python executed the same function faster than C++? Or am I reading it wrong?

like image 794
Snake2k Avatar asked Feb 28 '26 19:02

Snake2k


1 Answers

Remove all print statements - these cause the program to pause and you're benchmarking the time your system spends doing I/O which is highly variable and blankets any differences between your Python and your pure C++ runtime.

Try doing some heavy mathematical computation like finding the first 1000 primes for a more fair comparison.

Having said that, I don't expect your C++ program to outperform your Python program by much if at all. They should be neck-to-neck for the most part with the only possible disadvantage for Python being its interpreter's "boot-up" time.

like image 69
14 revs, 12 users 16% Avatar answered Mar 02 '26 09:03

14 revs, 12 users 16%