先编译在运行
from distutils.core import setup, Extension
from Cython.Build import cythonize
import numpy
setup(ext_modules = cythonize(Extension(
'dot_cython',
sources=['dot_cython.pyx'],
language='c',
include_dirs=[numpy.get_include()],
library_dirs=[],
libraries=[],
extra_compile_args=[],
extra_link_args=[]
)))
# dot_cython.pyx
import numpy as np
cimport numpy as np
cimport cython
@cython.boundscheck(False)
@cython.wraparound(False)
cdef np.ndarray[np.float32_t, ndim=2] _naive_dot(np.ndarray[np.float32_t, ndim=2] a, np.ndarray[np.float32_t, ndim=2] b):
cdef np.ndarray[np.float32_t, ndim=2] c
cdef int n, p, m
cdef np.float32_t s
if a.shape[1] != b.shape[0]:
raise ValueError('shape not matched')
n, p, m = a.shape[0], a.shape[1], b.shape[1]
c = np.zeros((n, m), dtype=np.float32)
for i in xrange(n):
for j in xrange(m):
s = 0
for k in xrange(p):
s += a[i, k] * b[k, j]
c[i, j] = s
return c
def naive_dot(a, b):
return _naive_dot(a, b)
python setup.py build_ext --inplace
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup(
name = 'helloworld',
ext_modules=cythonize([
Extension("helloworld", ["helloworld.pyx"]),
]),
)
编译:
python Setup.py build
安装:
python Setup.py install
安装后,会将在build/lib.???目录下生成的helloworld.pyd拷贝到Lib/site-packages
测试:
>>>import helloworld
>>>helloworld.SayHello()
hello,world
4.2 其次就是可以自己写Makefile进行编译
写Makefile的好处就是可以知道编译的实质:
下面是用于Windows下编译的Makefile,Makefile内容如下:
ALL :helloworld.pyd
helloworld.c : helloworld.pyx
cython -o helloworld.c helloworld.pyx
helloworld.obj :helloworld.c
cl -c -Id:\python27\include helloworld.c
helloworld.pyd :helloworld.obj
link /DLL /LIBPATH:d:\python27\libshelloworld.obj /OUT:helloworld.pyd
执行命令:
set PATH=D:\Python27\Scripts;%PATH%
nmake
进行编译,会在根目录下生成helloworld.pyd
linux下的Makefile和Windows下的类似,只是编译器不同而己,另外,生成的文件名为:helloworld.so,而不是helloworld.pyd
cpython语法