写一段 Cython 代码检测 ndarray 的 inner-loop 是否满足 C-contiguous 以决定是否向量化
解读
国内一线厂(字节、阿里、腾讯、华为、商汤、旷视)在招聘“高性能 Python/科学计算工程师”时,常把“能否在 Cython 层判断内存连续性并据此开启 SIMD”作为分水岭。
题目只要求“检测 inner-loop 是否 C-contiguous”,但面试官实际想看到三层能力:
- 对 ndarray 底层 strides 语义的精确理解;
- 在 Cython 中零开销拿到 PyArrayObject 字段;
- 写出编译期可折叠、运行期零 Python 调用的判断逻辑,为后续
prange+simd铺路。
注意:国内面试手写代码通常是在“牛客网白板”或“VSCode Remote + 共享屏幕”完成,不允许带文档,必须一次写对,因此模板要极简、无警告、可编译。
知识点
- PyArrayObject 的
strides与dims字段含义; - C-contiguous 的等价条件:
strides[ndim-1] == itemsize
且对于 i ∈ [0, ndim-2] 有
strides[i] == dims[i+1] * strides[i+1]; - Cython
cimport numpy as cnp与np.import_array()初始化; - 使用
const npy_intp*直接取 strides/dims,避免 Python 层对象; boundscheck(False)+wraparound(False)+cdivision(True)保证 inner-loop 无额外指令;- 编译命令(国内常用):
python -m pip install -e . --no-build-isolation
其中setup.py需加Extension(..., define_macros=[("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION")])以通过厂内安全编译检查。
答案
# file: _contig_check.pyx
# cython: language_level=3, boundscheck=False, wraparound=False, cdivision=True
import numpy as np
cimport numpy as cnp
cimport cython
from libc.stdint cimport int64_t
# 必须初始化 NumPy C-API
cnp.import_array()
@cython.always_inline
cdef inline bint is_inner_loop_c_contiguous(const cnp.ndarray arr) noexcept nogil:
"""
检测 inner-loop(最后一维)是否 C-contiguous。
返回 True 即可安全使用 `prange`+`simd` 向量化。
"""
cdef:
int ndim = cnp.PyArray_NDIM(arr)
const npy_intp *dims = cnp.PyArray_DIMS(arr)
const npy_intp *strides = cnp.PyArray_STRIDES(arr)
npy_intp itemsize = cnp.PyArray_ITEMSIZE(arr)
# 空数组或 0-D 标量视为 contiguous
if ndim == 0:
return True
# 先快速检查最后一维
if strides[ndim - 1] != itemsize:
return False
# 再检查前面维度的 stride 是否连续
cdef npy_intp expected_stride = itemsize
cdef int i
for i in range(ndim - 1, 0, -1):
expected_stride *= dims[i]
if strides[i - 1] != expected_stride:
return False
return True
# 暴露给 Python 的包装,方便单元测试
def decide_vectorize(cnp.ndarray arr):
return is_inner_loop_c_contiguous(arr)
对应 setup.py(国内面试现场需默写):
from setuptools import setup, Extension
from Cython.Build import cythonize
import numpy as np
ext = Extension(
"_contig_check",
sources=["_contig_check.pyx"],
include_dirs=[np.get_include()],
define_macros=[("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION")],
)
setup(ext_modules=cythonize(ext, compiler_directives={"language_level": 3}))
编译 & 快速验证:
$ python -m pip install -e . --no-build-isolation
$ python -c "import _contig_check, numpy as np; print(_contig_check.decide_vectorize(np.ones((100,200))))"
True
拓展思考
- 若数组是 Fortran-contiguous 但 inner-loop 长度=1,上述函数返回 False;
实际业务中可放宽为“仅保证最后一维 stride==itemsize”即可向量化,需与算法同学对齐。 - 当
ndim>3且仅 inner-most 维连续时,可结合prange做“分块+SIMD”,其余维走 stride 访问;
此时需把is_inner_loop_c_contiguous结果传给numba.jit或xsimd做二级调度。 - 国内厂内审计要求“零 deprecated API”,因此必须写
NPY_NO_DEPRECATED_API宏;
面试时若漏掉,会被直接追问“如何证明你的扩展在 numpy 2.0 不会 core dump”。 - 更高阶的考点:在
nogil块里把结果传给 OpenMPsimd指令,
示范代码:
现场若能写出with nogil: if is_inner_loop_c_contiguous(arr): # 告诉编译器可以向量化的 pragma # cython 会原样透传给后端 C 编译器 #pragma omp simd for i in range(n): ...#pragma omp simd并解释为何不用#pragma ivdep,可再拿一轮加分。