Photo by Jake Givens on Unsplash

https://medium.com/swlh/python-can-be-faster-than-c-2372c627068

Python is a great versatile programming language. Even though python is used most for machine learning problem solving because of its library and high-level language, it is known to be slower than many other languages. Because of its reputation, many would decide to leave the language behind and stick with other options like C++ for program solving.

In this article, I will show you how Python is faster than C++.

Basic Speed Testing

To test the normal speed difference between Python and C++, I will test the execution time of the Generation of primes algorithm. It is a simple algorithm with clear short steps in both languages.

Generation of primes flowchart

Python Implementation

import math
from time import per_counter def is_prime(num):
if num == 2:
return True;
if num <= 1 or not num % 2:
return False
for div in range(3,int(math.sqrt(num)+1),2):
if not num % div:
return False
return Truedef run program(N):
for i in range(N):
is_prime(i)if __name__ == ‘__main__’:
N = 10000000
start = perf_counter()
run_program(N)
end = perf_counter()
print (end — start)

C++ Implementation

#include <iostream>
#include <cmath>
#include <time.h>using namespace std;bool isPrime(int num)
{
if (num == 2) return true;
if (num <= 1 || num % 2 == 0) return false;
double sqrt_num = sqrt(double(num));
for (int div = 3; div <= sqrt_num; div +=2){
if (num % div == 0) return false;
}
return true;}int main()
{
int N = 10000000;
clock_t start,end;
start = clock();
for (int i; i < N; i++) isPrime(i);
end = clock();
cout << (end — start) / ((double) CLOCKS_PER_SEC);
return 0;}

Results

  • Python: 80.137 seconds
  • C++ : 3.174 seconds

Comment

As expected, C++ was 25 times faster than Python in our basic test. So the reputation is true, and this is logical as

  • Python is a dynamic language, unlike C++.
  • GIL (Python Global Interpreter) doesn’t allow parallel programming.

This speed difference can be fixed as python was created to be a flexible versatile language. One of the top solutions for the speed problem is using Numba.

Numba

Numba is an open source JIT compiler that translates a subset of Python and NumPy code into fast machine code. ~ Wikipedia

Briefly, Numba is a library that makes Python fast. It is very easy to use and dramatically change how fast your code. To start using Numba, just install it using the console use

pip install numba

Python Implementation After Using Numba

import math
from time import per_counter
from numba import njit, prange@njit(fastmath=True, cache=True)
def is_prime(num):
if num == 2:
return True;
if num <= 1 or not num % 2:
return False
for div in range(3,int(math.sqrt(num)+1),2):
if not num % div:
return False
return True@njit(fastmath=True, cache=True,parallel=True)
def run program(N):
for i in prange(N):
is_prime(i)if __name__ == ‘__main__’:
N = 10000000
start = perf_counter()
run_program(N)
end = perf_counter()
print (end — start)

Results

Python: 1.401 seconds
C++ : 3.174 seconds

So Python is faster than C++. So it is possible to speed up your algorithms in Python to be faster than C++.

Updates

I have published this article earlier, and I got a lot of comments that criticize how I handled the comparison. I thought about the comments a lot, and I see they have a lot of good views. So I first thought: maybe this article is harming more than benefiting anyone, so I should remove it. Yet, then I had the thought that the discussion that happened in the comments is truly useful to have in our tech articles. It is really positive to read something and have the knowledge to criticize from different points of view. So I decided that instead of removing this article, I will remind you to read the comments section. I will share the top comments I loved but first, let me explain myself little more.

Is the article says that Python is faster than C++?

The main misunderstanding that happened in this article, is thinking that I am saying that Python is faster than C++. And honestly, I didn’t say this. I said It “can” be. The possibility of this will happen for sure under certain conditions.

Why the comparison wasn’t fair, why not using parallelism in both codes?

Well, I loved this argument in the comments. Yet, my main goal of the article was to tell Python Developers how to make their code faster using Numba. I coded before in C++, and I did in Python too. C++ is an awesome language and it was the first programming language to use. Yet, Python is pretty useful in coding faster, the not faster performance of the code, but faster coding time of the project.

I know people that don’t know C++, and they learned Python and they do awesome with it. Yet, always people around them advise them to go to C++ to have a faster code. They forget that those people are experts in Python, and will be a total beginner in C++ if they did the shift. For those people, they won’t do parallelism in C++! So the comparison was for them.

Anyways, I am not here to define my opinion anymore. I hope you try Numba and enjoy a new way to code Python. Here are snippets of the top comments I loved — some comments are so tall, so I am sharing only snippets” :

1. By Jukka Aho:

This is a bit unfair comparison. Numba is JIT-compiling code in background, so actually you are now comparing two compiled languages, not the performance of Python itself.

2. By Andre Dias:

if C++ cached IsPrime , like you did in Python, things would change. This article should be renamed “Python can be nearly as fast as C++ with some clever programming”. This should be the point, Python is faster to prototype and develop in general, and “don’t worry, we can make it very fast later”.

3. By Carli* Freudenberg

Thanks for the comparision. Numba seems to be very easy to use. But still it is an unfair comparision: You compare a multi thread program with a single thread program. To really show that python is faster than C++ you would need to activate multi threading also for you C++ code.

4. By Bartosz Górski

No, its 100% unfair comparision. You compare multi-threaded, compiled and optimized Python code with bare, single threaded C++ code without providing compilation parameters. I’m pretty sure C++ code with optimization and multi threading can go lower than 1s.

5. By Santiago Hurtado

This sort of comparison are done to mislead and promote one self to people who don’t understand the topic throughly, but hey there is no peer reviews on medium.

You know what, I didn’t delete this article because of this comment! Yes, I want Medium to have a peer review spirit!

6. By Mateus Coutinho Marim

This experiment is biased, you cannot compare two things that run in different settings, so you cannot say in that case that python is faster than C++. But anyway, it was interesting, it’s nice to get to know numba.

I guess now it is a fair discussion to know what others said as well. I hope Numba will benefit you though.

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.