Python调用C库
2024-10-19 13:36:27
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
最新文章
- 用jquery实现瀑布流案例
- 极富创意的3D文件夹切换效果
- adb logcat 基本用法
- 中文在unicode中的编码范围
- CVE-2014-4113 windows通杀本地提权0day
- (转)Aspone.Cells设置Cell数据格式 Setting Display Formats of Numbers and Dates
- arm裸机驱动错误总结
- Kail安装Parallels tools
- SVN遇到的几个错误问题解决办法
- 虚拟机NAT模式主机ping不通虚拟机解决方案
- 博文Contents<;451--到999—>;
- 吾八哥学Python(四):了解Python基础语法(下)
- [Cordova inAppBrowser 在App内打开浏览器]
- VScode 中 vue文件template中不能使用tab补齐标签
- 前端JS插件整理
- vue-cli: preset预设
- frame与iframe的区别及基本用法
- djiango控制语句
- hql语句加别名的错误
- BZOJ4524 CQOI2016伪光滑数(堆)