Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ execution time is slower than python's

Tags:

c++

python

I switched to c++ because i heard its 400 times faster than python, But when i made an infinite loop that increments a variable and prints its value python seems to be faster, How can that be? And how to optimize it?

Python script:

x = 1
while 1:
    print(x)
    x+=1

C++ code:

int x = 1;
while (1) {
cout << x << endl;
x++;
}

I tried optimizing it by putting this command:

ios_base::sync_with_stdio(false);

The speed became almost identical to python's but not faster.

Yeah and i did search for this topic i didn't find anything that explains why.

like image 373
xMsid Avatar asked Dec 03 '25 18:12

xMsid


1 Answers

C++'s std::endl flushes the stream, python's print does not. Try using "\n", that should speed up the C++ code.

like image 106
Doncho Gunchev Avatar answered Dec 06 '25 08:12

Doncho Gunchev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!