mau5padd
mau5padd

Reputation: 405

Speed of Python Extensions in C vs. 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?

Upvotes: 15

Views: 3186

Answers (2)

NothingMore
NothingMore

Reputation: 1281

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.

Upvotes: 16

Borealid
Borealid

Reputation: 98459

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.

Upvotes: 6

Related Questions