附录B:类型速查表
本附录提供类型相关快速参考。
Python-Cython类型对照
Section titled “Python-Cython类型对照”功能说明:Python类型与Cython类型的对应关系。
| Python | Cython | C类型 | 说明 |
|---|---|---|---|
int | int | int | 32位整数 |
int | long | long | 平台相关 |
int | long long | int64_t | 64位整数 |
float | float | float | 32位浮点 |
float | double | double | 64位浮点 |
str | str | PyObject* | Unicode字符串 |
list | list | PyObject* | 动态数组 |
dict | dict | PyObject* | 哈希表 |
bool | bint | int | 布尔值 |
bytes | bytes | char* | 字节数组 |
常用类型声明
Section titled “常用类型声明”功能说明:常见类型声明示例。
# 变量声明cdef int x = 10cdef double pi = 3.14159cdef str name = "Cython"cdef bint flag = True
# 指针声明cdef int* ptrcdef double* d_ptrcdef char* c_str
# 数组声明cdef int arr[10]cdef double matrix[3][4]
# typed memoryviewcdef double[:] vec1dcdef int[:, :] mat2d性能提示速查
Section titled “性能提示速查”功能说明:不同类型的性能差异。
| 模式 | 性能 | 说明 |
|---|---|---|
| C类型(int/double) | 最快 | 无GC开销 |
| typed memoryview | 极快 | 零拷贝数组 |
| Python对象 | 慢 | 有GC开销 |
| GIL操作 | 中 | Python/C切换 |
性能优化原则:
- 数值计算用C类型
- 大数组用typed memoryview
- 避免Python对象和C类型混合
- 热点代码用
nogil
函数类型速查
Section titled “函数类型速查”功能说明:函数定义类型对比。
| 声明 | Python调用 | C调用 | 性能 |
|---|---|---|---|
def | Yes | No | 慢 |
cpdef | Yes | Yes | 中 |
cdef | No | Yes | 最快 |