How Slow is Python Compared to C

45,000 times slower!

Peter Xie
4 min readJul 13, 2020

--

OMG
Photo by Ben White on Unsplash

To compare the computation performance between Python and C languages, let’s do a loop for sum in one second. The code itself is pretty much self-explanatory.

Python

Run:

time python python_loop.py 10000000
real 0m1.044s
user 0m1.004s
sys 0m0.004s

It is 10 millions loops in a second for Python. It sounds not bad.

C

Compile in normal mode:

gcc c_loop.c -o c_loop

Run:

time ./c_loop 450000000
s: 450000000
real 0m1.032s
user 0m1.008s
sys 0m0.008s

It is 450 million loops in a second, which is 45 times faster than Python.

Furthermore, C can be compiled in optimized mode for a better performance.

Compile:

gcc -O3 c_loop.c -o c_loop

Run:

time ./c_loop 450000000
real 0m0.001s
user 0m0.000s
sys 0m0.000s

Yes, it is unbelievable! It is 1000 times faster than normal mode, and 45,000 times faster than Python.

Note that the optimization is not always 1000 times faster for all C code, but it should be at least 10 times faster, so it is still hundreds of times faster than Python. Also bear in mind that the speed difference between C and Python varies on different code.

Javascript

Okay, let’s make a fair comparison between script (interpreted) languages Python v.s. Javascript.

--

--

Peter Xie

Code Simple | Python and AI Enthusiast | peter.jp.xie@gmail.com