busukxuan busukxuan - 2 months ago 6
Python Question

Python faster than C++? How does this happen?

I'm using Windows7 using CPython for python3.22 and MinGW's g++.exe for C++ (which means I use the libstdc++ as the runtime library). I wrote two simple programs to compare their speed.


while x!=1000000:


#include <iostream>
int main()
int x = 0;
while ( x != 1000000 )
std::cout << x << std::endl;
return 0;

Both not optimized.

I ran c++ first, then i ran python through the interactive command line, which is much slower than directly starting a .py file.

However, python outran c++ and turned out to be more than twice as fast. Python took 53 seconds, c++ took 1 minute and 54 seconds.

Is it because python has some special optimization done to the interpreter or is it because C++ has to refer to and std which slows it down and makes it take up ram?

Or is it some other reason?

Edit: I tried again, with
instead of
, and compiling with the
flag, this time it took 1 min to reach 500,000.


There isn't anything obvious here. Since Python's written in C, it must use something like printf to implement print. C++ I/O Streams, like cout, are usually implemented in a way that's much slower than printf. If you want to put C++ on a better footing, you can try changing to:

#include <cstdio>
int main()
    int x=0;
        std::printf("%d\n", x);
    return 0;

I did change to using ++x instead of x++. Years ago people thought that this was a worthwhile "optimization." I will have a heart attack if that change makes any difference in your program's performance (OTOH, I am positive that using std::printf will make a huge difference in runtime performance). Instead, I made the change simply because you aren't paying attention to what the value of x was before you incremented it, so I think it's useful to say that in code.