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

最新文章

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

热门文章

  1. 阿里Android一面(校招)
  2. 字符串String类
  3. React Native-目前最火的前端技术?
  4. BZOJ 3675: [Apio2014]序列分割( dp + 斜率优化 )
  5. JavaScript学习笔记2-数组对象
  6. 我的Python成长之路---第八天---Python基础(24)---2016年3月5日(晴)
  7. poj 1838
  8. 谈谈Facebook的聊天系统架构
  9. Bosch 英语面试准备分享
  10. poj 3176 Cow Bowling(区间dp)