您的位置:首页 > 编程语言 > Python开发

Python调用C库

2016-04-30 02:28 441 查看

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: