Cpython

先编译在运行

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语法

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值