if (!PyArg_ParseTuple(args, "OO", &list_a, &list_b)) { returnNULL; }
Py_ssize_t size = PyList_Size(list_a); PyObject* result = PyList_New(size);
for (Py_ssize_t i = 0; i < size; i++) { double a = PyFloat_AsDouble(PyList_GetItem(list_a, i)); double b = PyFloat_AsDouble(PyList_GetItem(list_b, i)); PyList_SET_ITEM(result, i, PyFloat_FromDouble(a + b)); }
# Python 版本 defpy_add(a, b): return [x + y for x, y inzip(a, b)]
# C 扩展版本 import fastmath
import time import random n = 10**6 a = [random.random() for _ inrange(n)] b = [random.random() for _ inrange(n)]
t1 = time.perf_counter() c1 = py_add(a, b) print(f'Python: {time.perf_counter()-t1:.3f}s')
t2 = time.perf_counter() c2 = fastmath.vector_add(a, b) print(f'C 扩展: {time.perf_counter()-t2:.3f}s')
🔄 Cython(更简单的方式)
如果不想直接写 C 代码,可以用 Cython:
1 2 3 4 5 6 7 8
# fastcython.pyx def vector_add(list a, list b): cdef int i cdef int n = len(a) cdef list result = [0.0] * n for i in range(n): result[i] = float(a[i]) + float(b[i]) return result
1 2 3 4 5 6 7 8
# setup.py from setuptools import setup from Cython.Build import cythonize