I’m using Windows 7 using CPython for Python 3.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.
Python:
x=0
while x!=1000000:
x+=1
print(x)
C++:
#include <iostream>
int main()
{
int x = 0;
while ( x != 1000000 )
{
x++;
std::cout << x << std::endl;
}
return 0;
}
Both are not optimized.
I ran C++ first, and then i ran Python through the interactive command line, which is much slower than directly starting a .py file.
However, Python outran C++, and it turned out to be more than twice as fast. Python took 53 seconds, and 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 <iostream> and std which slows it down and makes it take up RAM?
Or is it some other reason?
I tried again, with \n instead of std::endl, and compiling with the -O3 flag. This time it took 1 minute to reach 500,000.
There isn’t anything obvious here. Since Python’s written in C, it must use something like
printfto implementprint. C++ I/O Streams, likecout, are usually implemented in a way that’s much slower thanprintf. If you want to put C++ on a better footing, you can try changing to:I did change to using
++xinstead ofx++. 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 usingstd::printfwill make a huge difference in runtime performance). Instead, I made the change simply because you aren’t paying attention to what the value ofxwas before you incremented it, so I think it’s useful to say that in code.