来源: https://zhuanlan.zhihu.com/p/24311879 ;
https://moonlet.gitbooks.io/cython-document-zh_cn/content/ch3-using_c_libraries.html
https://www.jianshu.com/p/cfcc2c04a6f5
学习
- CSDN今天登不上去,不能创作
- sogou输入法偷偷上传数据,占用带宽大,小狼毫是繁体输入,很不适应。
- cython, 可以看成一个python语言扩展集合,通过定义c外部库函数的声明,将c库中的函数引用进来,但是最好将函数类型显式声明,编译器好处理,速度快,否则在运行时需要类型检查。cython有两种文件后缀,一个是pyx是源文件,一个是pyd是声明文件。通过setup.py可以编译成.so文件。
- cython编译后的c代码的速度不一定比numpy快。
- cython 引用c库函数,需要c库函数在系统默认库路径或者自定义位置,在setup中可以指明。
- Cython 提供了一个很好的工具,可以方便地检查 Cython 程序中哪里可能可以进一步优化。
- cython可以用
cdef extern from "math.h": double sin(double x)
引用外部头文件 - 可以引用类型模板
ctypedef fused my_type: int double long long
https://cython.readthedocs.io/en/latest/src/userguide/numpy_tutorial.html
-
函数需要多少就用多少,定义类后,将C里面的函数包装起来就好了
10.本来我想胶水这一部分也像前面性能提升部分一样详细地写出来。后来想想,其实这一部分主要涉及的就是 Cython 语法本身,没有什么特别值得注意的,所以看看 Cython 文档就好了。我这里把一些特性不完全地列出来:函数签名基本上可以原样从 C/C++ 复制到 Cython 中
C 中的 _Bool 类型和 C++ 中的 bool 类型在 Cython 中都用 bint 取代(因为 Python 没有布尔类型)struct / enum / union 是支持的const 限定和引用都是支持的命名空间是支持的C++ 类是支持的部分操作符重载是支持的,部分操作符需要改名内嵌类是支持的模板是支持的异常是支持的构造函数、析构函数是支持的静态成员是支持的libc / libcpp / STL 是支持的声明写在 .pxd 中可以在 .pyx 中 cimport 进来你可能需要注意 Python 字符串到各式各样的 C/C++ 字符串的转换 -
你需要考虑的内容有:broadcast,type cast, 内存管理, 异常处理, buffer大小,模板支持,重载支持,大数溢出是否会自动改变变量类型,如同numba。转换到c语言的速度,多线程支持
-
numba支持的python语言特性有?支持的第三方数学包有?支持的类型有?numba支持的ufunc有?numba支持的numpy函数有?numba(cuda)支持的python特性有?numba支持的原子操作有?
-
不同的包的类型如何转换是个问题。
-
Python math 模块提供了许多对浮点数的数学运算函数。
Python cmath 模块包含了一些用于复数运算的函数。
cmath 模块的函数跟 math 模块函数基本一致,区别是 cmath 模块运算的是复数,math 模块运算的是数学运算。 -
从目前来看,GPU适合于大矩阵元素级别的简单运算,不能有逻辑运算参与。
16 numba GPU支持特性:Due to the CUDA programming model, dynamic memory allocation inside a kernel is inefficient and is often not needed. Numba disallows any memory allocating features. This disables a large number of NumPy APIs. For best performance, users should write code such that each thread is dealing with a single element at a time. 在核函数内的动态内存分配效率低下,不需要。numba不允许,所以用于应该写一种处理单个元素的函数
可以访问accessing ndarray attributes .shape, .strides, .ndim, .size, etc.
可以使用scalar ufuncs that have equivalents in the math module; i.e. np.sin(x[0]), where x is a 1D array.
可以索引indexing and slicing works.
不支持:array creation APIs.array methods.functions that returns a new array.
math,cmath,operator大多支持
内置类型:int
float
complex
bool
None
tuple
不支持:try,with,list,dict, set or generator comprehensions, yield
支持raise,print -
想要numpy在GPU上跑,需要Cupy。cupy也有很多数学函数。
-
但是也有人主张用torch
浙公网安备 33010602011771号