学习python是一个令人振奋不已的过程,python是一个如此powerfull的高级语言,简单却功能强大,库多而又功能齐全,几乎可以帮助我们完成任何一项工作。它唯一的缺陷就是跑得慢,在跑得慢的问题上,它有有着令人振奋的解决方案,嵌入c/c++代码的方法。一个程序80%的时间运行在20%的代码上,我们只要用c重写那20%的代码,便可缔造完美程序。
除了运行速度问题,还有其他可以用c来增强的功能。如python2.5可递归栈的最大层次是999,而c却远远大于这个限制。
除了运行速度问题,还有其他可以用c来增强的功能。如python2.5可递归栈的最大层次是999,而c却远远大于这个限制。
exmaple.c
- /*
- * =============================================================================
- ========
- *
- * Filename: example.c
- *
- * Description: embed c in python
- *
- * Version: 1.0
- * Created: 2008年12月15日 20时48分19秒
- * Revision: none
- * Compiler: gcc
- *
- * Author: Li WeiJian (mn), lwj1396@163.com
- * Company: hunan university
- *
- * =============================================================================
- ========
- */
- int fact(int n)
- {
- if(n <= 1)
- return 1;
- else
- return n*fact(n-1);
- }
wrap.c
- /*
- * =============================================================================
- ========
- *
- * Filename: wrap.c
- *
- * Description: c and python
- *
- * Version: 1.0
- * Created: 2008年12月15日 20时49分11秒
- * Revision: none
- * Compiler: gcc
- *
- * Author: Li WeiJian (mn), lwj1396@163.com
- * Company: hunan university
- *
- * =============================================================================
- ========
- */
- #include<Python.h>
- //导出函数
- PyObject *wrap_fact(PyObject* self,PyObject* args)
- {
- int n,result;
- if (!PyArg_ParseTuple(args,"i:fact",&n))
- return NULL;
- result=fact(n);
- return Py_BuildValue("i",result);
- }
- //方法列表
- static PyMethodDef exampleMethods[]=
- {
- {"fact",wrap_fact,METH_VARARGS,"Caculate N!"},
- {NULL,NULL}
- };
- //初始化函数
- void initexample()
- {
- PyObject* m;
- m=Py_InitModule("example",exampleMethods);
- }
编译
gcc -fpic -c -I/usr/include/python2.5 /
-I /usr/lib/python2.5/config /
example.c wrapper.c
gcc -shared -o example.so example.o wrapper.o
fact.py
- import example
- import datetime
- def fact(n):
- if n<=1:return 1
- else:return n*fact(n-1)
- if __name__=='__main__':
- now=datetime.datetime.now()
- for i in range(10000):
- n=fact(100)
- end=datetime.datetime.now()
- print 'the python fact takes:',end-now
- for i in range(10000):
- n=example.fact(100)
- print 'the c fact taks:',datetime.datetime.now()-end
运行结果:
lwj@lwj-desktop:~/code/python$ python fact.py
the python fact takes: 0:00:01.214449
the c fact taks: 0:00:00.121041
c要快了》10倍。不过还没测试过单纯的c的环境。。。有空再测测。。。。
另外python本身只能递归999层深度
c没有这个限制