运行的Cython的3种方法


运行条件:python2.7

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

第一种:

fib.pyx

def fib(long n):
    '''Returns the nth Fibonacci number.'''
    cdef long a=0, b=1, i
    for i in range(n):
        a, b = a + b, a
    return a


test.py

import sys  
reload(sys)  
sys.setdefaultencoding('utf8')  
import pyximport; pyximport.install()

import fib
print fib.fib(15)

运行方法:

python test.py

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

第二种

fib.pyx

def fib(long n):
    '''Returns the nth Fibonacci number.'''
    cdef long a=0, b=1, i
    for i in range(n):
        a, b = a + b, a
    return a

setup.py

#!/usr/bin/python
#-*-coding:utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
from distutils.core import setup
from Cython.Build import cythonize
#cythonize:编译源代码为C或C++,返回一个distutils Extension对象列表
setup(ext_modules=cythonize('fib.pyx'))

test.py

from fib import fib
print fib(9)

运行方法:

python setup.py build_ext --inplace
python test.py

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

第3种

c1.pyx

import math

def great_circle(float lon1,float lat1,float lon2,float lat2):
    cdef float radius = 3956.0
    cdef float pi = 3.14159265
    cdef float x = pi/180.0
    cdef float a,b,theta,c

    a = (90.0-lat1)*(x)
    b = (90.0-lat2)*(x)
    theta = (lon2-lon1)*(x)
    c = math.acos((math.cos(a)*math.cos(b)) + (math.sin(a)*math.sin(b)*math.cos(theta)))
    return radius*c


test.py

#!/usr/bin/env python  
#encoding: utf-8
import sys   #引用sys模块进来,并不是进行sys的第一次加载
reload(sys)  #重新加载sys
sys.setdefaultencoding('utf8')  ##调用setdefaultencoding函数
import timeit
from c1 import great_circle
num=10#表示运行多少次
# t = timeit.Timer("c1.great_circle(%f,%f,%f,%f)" % (lon1,lat1,lon2,lat2),"import c1")
t = timeit.Timer("c1.great_circle(%f,%f,%f,%f)" % (16,124,76,173),"import c1")
print "Cython function (still using python math)", t.timeit(num), "sec"

运行方法:

cython c1.pyx
gcc -c -fPIC -I/usr/include/python2.7/ c1.c
gcc -shared c1.o -o c1.so
python test.py



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值