运行条件: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