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.
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 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 \n
instead of std::endl
, and compiling with the -O3
flag, this time it took 1 min to reach 500,000.