[Cython篇] hello world - tsungjung411/python-study GitHub Wiki

Basic Tutorial

helloworld.pyx

print("Hello World")

setup.py

from setuptools import setup
from Cython.Build import cythonize

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

編譯 helloworld.pyx

$ pip install Cython
$ python setup.py build_ext --inplace

測試 helloworld

import helloworld  # print Hello World

【工程師實用外掛】開啟 Cython,讓你的 Python 運算速度提升 36 倍!

run_cython.pyx

cpdef int test(int x):
    cdef int y = 1
    cdef int i
    for i in range(1, x+1):
      y *= i
    return y

setup.py

from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize('run_cython.pyx'))

編譯 run_cython.pyx

$ pip install Cython
$ python setup.py build_ext --inplace

測試 run_cython

import run_cython
run_cython.test(5)  # =120