List vs Array

Is Cython Faster Than C?

Cython is usually no faster than hand-written C. Untyped code stays slow, and typed loops can get close to C speed. Here is what to expect and why.

On this page
  1. The short answer
  2. What Cython is
  3. Why untyped Cython is slow
  4. Typed Cython can get close to C
  5. Why C is still the reference point
  6. For C++ readers

The short answer

Not in general. Cython is usually no faster than hand-written C. Code without type declarations is much slower, because every value is a Python object. Code with C types declared can get close to C speed, but it rarely beats well-written C.

What Cython is

Cython is a superset of Python. Most Python code is valid Cython, and Cython adds C types and C-style declarations. You write .pyx files, Cython translates them into C, and a C compiler builds that C into an extension module that Python can import.

Why untyped Cython is slow

Without type declarations, a variable can hold any Python object. Each operation then goes through Python’s object handling, which costs time even for simple arithmetic. Compiling the file does not remove that cost by itself.

Typed Cython can get close to C

Declaring C types lets Cython compile loops down to plain C:

def sum_to(int n):
    cdef long total = 0
    cdef int i
    for i in range(n):
        total += i
    return total

The loop itself becomes a plain C loop. The function is still called from Python, so there is some call overhead, but the work inside the loop runs close to C speed.

Why C is still the reference point

Hand-written C can do the same operations with no translation step. Cython’s generated C may be less tidy than what a person writes, and every crossing between Python and Cython adds some cost. So the best Cython can usually do is match C, not beat it.

Where the time goes matters more than the language. A Python list holds references to objects, so a loop over one follows a pointer for every element. A C array of int values sits together in memory. For that reason, the container you pick often matters more than the language, as the list vs array c discussion in C++ shows. Speed comparisons between languages are easy to get wrong, so for another example, see “rust vs c performance.”

For C++ readers

C++ compiles straight to machine code with no Python layer, so C++ and C usually run at similar speed for comparable low-level code. If you need Python to call C++ code, pybind11 is a common route, and Cython is another.

The complete guide to list vs array

List vs Array in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

Enums in C++ With Examples

Learn enums in C++ with clear examples: syntax, automatic values, enum class, switch statements, underlying types, and common mistakes to avoid.

Enums 5 min read