15

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?

3
  • Maybe you should consider Cython if you think about writing extensions/modules/... Commented Feb 19, 2012 at 1:46
  • @hochl -- Isn't Cython just regular Python? As opposed to Jython or IronPython? Commented Feb 19, 2012 at 5:19
  • Cython is like Python code that can be compiled for speedup. In most situations you gain a speedup between 20 to 50 times. See cython.org. Commented Feb 19, 2012 at 12:22

2 Answers 2

16

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.