When The Interpreter Loses To The Compiler…
When learning programming, one of the first things you read about are language processors. These processors are of three main types:
- Compilers
- Interpreters
- Assemblers
Out of these, compiled languages historically tend to be faster than interpreted ones.
However, I believed — like my teacher said — that modern interpreters had become almost as fast as compilers. That is, until I tried calculating Armstrong numbers in Python. Here’s what happened…
The Challenge
We had been tasked with writing a Python program to check if a given number is an Armstrong Number. I was quite sure that Python would easily handle this, but I was in for a huge shock!
Here’s the code I used-
import time
start_time = time.time()
powers = {length: {digit: digit ** length for digit in range(10)} for length in range(1, 10)}
for num in range(0,500000000):
n = num
nos = str(n)
length = len(nos)
sum = 0
while n > 0:
rem = n%10
n //= 10
sum += powers[length][rem]
if sum > num:
break
if sum == num:
print(sum)
end_time = time.time()
time_taken = end_time - start_time
print(f"The time taken is {time_taken} seconds.")
The Shocking Performance
The logic of this program was quite simple, so I expected it to work with ease. I clearly did not expect Python to struggle so much with it.
At first, the numbers appeared quite quickly.
But as the range increased, the program began to slow down — drastically. What started as a smooth operation soon became a crawl, with new numbers appearing after intervals that felt like years.
I couldn’t believe that Python, a language known for its ease of use and versatility, was struggling so much.
Python finally managed to complete the task in 1020.918277 seconds, or about 17 minutes.
Enter C++
I have this one friend, who keeps insisting that C++ is better than Python. I went to him and explained my situation. He had been waiting for a situation like this!
With an smug grin, he asked me to try it out in C++. Since I wasn’t as familiar with C++, I asked him to draft the code and send it over.
The result flabbergasted me!
C++ took ONLY 3979 milliseconds to print 30 Armstrong Numbers, while Python struggled for 1020.9 seconds.
It’s not even comparable!
What I learnt from this was that, while interpreted languages like Python are great for ease of development, readability, etc, compiled languages like still C++ reign supreme where speed is important, especially with a large number of computations.
I think it’s safe to say that the compiler completely obliterated the interpreter in this situation.
Cheers,
Aarav Iyer
Note:
- While compiling the C++ code, I used the
O3
optimization level to ensure the fastest execution time.