Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speed of Python Extensions in C vs. C

Tags:

python

c

Python extension modules written in C are faster than the equivalent programs written in pure Python. How do these extension modules compare (speed wise) to programs written in pure C? Are programs written in pure C even faster than the equivalent Python extension module?

like image 422
mau5padd Avatar asked Feb 18 '12 23:02

mau5padd


People also ask

How much faster is C compared to Python?

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.

Is Python as fast as C?

Python is an excellent tool enabling just that. It allows for focusing on the idea itself and not be bothered with boilerplate code and other tedious things. However, Python comes with a major drawback: It is much slower than compiled languages like C or C++.

Are for loops faster in C than Python?

The C code will be significantly faster even if compiled completely unoptimized. Because python is a higher level language, there's a lot of computational and representational baggage in python that isn't present in C. A loop void of content exposes a lot of that baggage.

Which is faster C or C++ or Python?

After compiling, if you run the code, it takes about 2.42 seconds to generate all 67 million 13-mers. It means Python takes 25 times more time to run the same algorithm compared to C++.


2 Answers

How do these extension modules compare (speed wise) to programs written in pure C?

They are slightly slower due to the translation between Python data structures -> C types. Disregarding this translation the actual C code runs at exactly the same speed as a regular C function would.

Are programs written in pure C even faster than the equivalent Python extension module?

C programs (written entirely in C) can be faster than Python programs using the C extension modules. If the C program and the extension module are written with the same level of complexity, coder skill, algorithmic complexity, etc., the C program will win every time. However, if you're not a C guru and you're competing with a highly optimized Python C extension Python could be faster.

like image 126
NothingMore Avatar answered Oct 11 '22 04:10

NothingMore


Being a Python extension doesn't affect the execution speed of a piece of code, except insofar as the Python invoking it is slower than the equivalent C would be, and the compiler is less able to aggressively unroll and inline code which crosses the C/Python boundary.

That is to say, if you just have Python code call a C function, and then you do all your work in that function, the only performance difference is going to be the amount of time you spent before getting into the C side of things. From that point on, it is native C.

like image 39
Borealid Avatar answered Oct 11 '22 05:10

Borealid