C++ is faster, bro
2025-02-18
Being in college, every day is a hunt to learn more — and crash my PC more (I use FreeBSD, btw).
In my college, Python is the go-to language. Everyone is a fan of it. “C++ is just too difficult,” they claim, without even taking a look at the C++. Welp, a small price to pay for that juicy-juicy performance , right ?
Game ON : Python or C++
It’s a common belief that C++ is faster than Python — and for good reason. C++ compiles to machine code, while Python is interpreted. It’s like comparing a race car to a bicycle.
One is human-readable and one looks nerd-readable?..

So , I wrote a teeny tiny program , on both languages to test the speed.
for n in range(1<<30)
print(n)
and for the next contesant:
#include<iostream>
int main(void){
for(auto i = 0; i < 1 << 30; ++i){
std::cout << i << std::endl;
}
}
Now lets look at the time it took for each.
C++

Python

Woah woah, C++ was slower??. How would this happen..?
Even though LOT of CODE is spun out. we are only interested in this bit:

In L6 tag, a register r12d is incremented (add r12d , 1) and in the last it is compared to value of 1 << 30 and jumps another label if not equal. or continue looping. This label is done a billion times since it is a critical element to the program.
But what we are actually looking for are the calls to put() and flush().
You see, in the name of performance, filesteams are written using buffer. Instead of writing directly to a filepointer with each character. The character are accumulated to a buffer and flushed all at once to the filestream.
According to the generated assembly, we are flushing a billion times, which ultimately defeats the purpose of buffering the output and thus the bad performance.
BUT g(++) , where are we calling the flush() in our code ??
The culprit is std::endl; although it seems like it is to add a newline ,it also flushes to complete the buffering mechanism.
std::endl is more or less is std::puts(‘\n’) + std::flush()
To avoid this, we way do:
#include<iostream>
int main(void){
for(auto i = 0; i < 1 << 30; ++i){
std::cout << i << '\n';
}
}
Now the performance is

damn..
What’s the takeaway.
It doesn’t matter if a said language is faster (compiled or no), unless you can code good. New news are spreading each day on how we need more computational power the things we need to achieve (AI for an example), while companies like DeepSeek just surprised everyone.
Don’t learn to code, learn to understand what the code will do in the machine not just logically.
Learn to talk with the machine and understand.