qed
qed

Reputation: 23134

How does cython improve performance of pure python code

Here is the code:

## x.py
#!/usr/bin/env python3

for i in range(9999):
    for j in range(1, 9999):           
        pass

## x1.pyx
#!/usr/bin/env python3

# cdef double total = 0.0
# cdef int i, j
for i in range(9999):
    for j in range(1, 9999):          
        pass

## setup.py 

from distutils.core import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("x1.pyx")
)

In shell:

➜  /tmp  python3 setup.py build_ext --inplace
➜  /tmp  time python3 -c "import x1"
python3 -c "import x1"  2.86s user 0.01s system 99% cpu 2.875 total
➜  /tmp  time ./x.py
./x.py  4.94s user 0.01s system 99% cpu 4.961 total

It looks like cython brings a 2x performance boost even without touching static typing, how does it do this? Does this mean it will universally improve performance of pure python code?

Upvotes: 1

Views: 169

Answers (1)

poke
poke

Reputation: 388153

Cython translates Python code into actual C, so it can run at a level very close to native code. So any drawback from the dynamic Python interpreter you have with normal Python code is gone. This allows Cython code to be a lot faster, especially for such tasks as your example shows which is purely utilizing the CPU alone.

Upvotes: 4

Related Questions