如何用C/Cython加速Python代码?

进阶Python

答题要点

# Cython示例
# fast_compute.pyx
cdef int compute(int n):
    cdef int i, result = 0
    for i in range(n):
        result += i * i
    return result

def py_compute(n):
    return compute(n)

# setup.py
from setuptools import setup
from Cython.Build import cythonize

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

# 编译:python setup.py build_ext --inplace

# numba JIT编译(更简单)
from numba import jit, njit

@njit  # nopython模式,最快
def fast_sum(arr):
    total = 0
    for i in range(len(arr)):
        total += arr[i]
    return total

# NumPy向量化(最简单)
import numpy as np
result = np.sum(arr ** 2)  # C实现,已经很快

# ctypes调用C库
from ctypes import cdll, c_int
lib = cdll.LoadLibrary('./mylib.so')
lib.my_function.argtypes = [c_int]
lib.my_function.restype = c_int
result = lib.my_function(42)

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题

回知识库看这一块

同一能力的其他题