我有以下对数组求和的最小示例(取自here):
#lib.cpp
template<typename T>
T arr_sum(T *arr, int size)
{
T temp=0;
for (int i=0; i != size; ++i){
temp += arr[i];
}
return temp;
}
#lib_wrapper.pyx
cimport cython
ctypedef fused float_t:
cython.float
cython.double
cdef extern from "lib.cpp" nogil:
T arr_sum[T](T *arr, size_t size)
def py_arr_sum(float_t[:] arr not None):
return arr_sum(&arr[0], arr.shape[0])
#setup.py
from setuptools import setup
from setuptools.extension import Extension
from Cython.Distutils import build_ext
import numpy as np
ext_modules = [Extension("lib_wrapper", ["lib_wrapper.pyx"],
include_dirs=[np.get_include()],
extra_compile_args=["-std=c++11", "-O1"],
language="c++")]
setup(
name='Rank Filter 1D Cython',
cmdclass={'build_ext': build_ext},
ext_modules=ext_modules
)
应用
python setup.py build_ext --inplace
会生成一个202K大小共享对象lib_wrapper.cpython-39-darwin.so。 gcc -shared -fPIC -O1 -o lib.so lib.cpp
会产生一个 ~4K 大小 的较小物体。
我假设文件大小的冗余来自 Cython 创建的 C++-Python 桥。
考虑到 Numpy-C API、pybind11 等众多方法,哪一种可以允许在没有如此大的文件大小开销的情况下创建此桥?请从建议中排除 ctypes - 它似乎会大大增加访问时间。
Python C API 和 Numpy C API 将具有最小的大小,因为其他所有内容都只是它们的包装。
要减少 C++ 二进制文件的大小,最好的技巧是
-Os
而不是任何其他 -Ox
标志。-fno-rtti
-g
标志)