Python调用C库
Python可以利用ctypes库很方便地调用C的库函数。 C库例程:
# file: a.c
int sum(int a, int b){
int t = 0;
int i = 0;
for(; i < b;i++) t += a;
return t;
}
shell> gcc -fPIC -g -c -Wall a.c && gcc -shared -Wl,-soname,liba.so -o liba.so a.o
Python程序例程:
# file: a.py
import timeit
n=1000000
def s(a,b):
t = 0
for i in xrange(b):
t += a
return t
print s(10,100)
t = timeit.Timer("s(10,20)", "from __main__ import s")
print t.timeit(n)
del s
import ctypes
a = ctypes.cdll.LoadLibrary("./liba.so")
s = a.sum
print s(10,100)
t = timeit.Timer("s(10,20)", "from __main__ import s")
print t.timeit(n)
运行比较:
shell> python2.6 a.py
1000
1.94600701332
1000
0.611714839935
时间: 2024-12-30 04:11:03