Python性能提升一 —— 高计算模块使用C++编写
2013-09-26 16:33
731 查看
场景
假设有一个高计算场景:双层循环,复杂度O(n*n),并且n足够大。纯python方式
def func(times): s = 0 for i in range(times): for j in range(times): s += i*j return s
Python + C++库方式
高计算模块放到C++库中long long TestFact::func(int n) { long long lResult = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) lResult += i*j; return lResult; }
两种方式性能对比
附完整代码
C++库代码#include <Python.h>
class TestFact{
public:
TestFact(){};
~TestFact(){};
long long func(int n);
};
long long TestFact::func(int n) { long long lResult = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) lResult += i*j; return lResult; }extern "C"
long long func(int n)
{
TestFact t;
return t.func(n);
}
编译成so库
g++ -fPIC -shared example.cpp -o example.so -I/usr/local/include/python2.6
Python代码
#!/usr/bin/python
#coding: utf-8
import os, time
import ctypes
def func(times): s = 0 for i in range(times): for j in range(times): s += i*j return s
def main():
n = 20000
start = time.time()
s = func(n)
elapsed = time.time() - start
print 'Pure Python: Result:%d, Time elapsed: %f s' % (s, elapsed)
pdll = ctypes.CDLL('./example.so')
pdll.func.restype = ctypes.c_longlong
start = time.time()
s = pdll.func(n)
elapsed = time.time() - start
print 'Python + C++: Result:%d, Time elapsed: %f s' % (s, elapsed)
if __name__ == '__main__':
main()
相关文章推荐
- 使用C/C++代码编写Python模块
- 扩展Python__在python脚本中使用其他语言(c/c++/java/c#)编写的模块
- 利用C++ Boost编写扩展Python模块
- Python 扩展使用 C/C++ 给 Python 写扩展模块的方法
- 使用C++创建Pyd文件扩展Python模块
- Python中使用urllib2模块编写爬虫的简单上手示例
- python中使用time模块计算代码执行效率的精度测试
- 使用 Boost.Python 嵌入 Python 模块到 C++
- 使用本地c/c++提升iOS性能 之一
- 使用 C++ 的 StringBuilder 提升 4350% 的性能
- 使用Python的base64 编码模块,编写去除 “=”的解码函数
- python中使用time模块计算代码执行效率的精度测试(转)
- 使用python编写一个监控使用内存并使用flask模块出图
- 使用本地c/c++提升iOS性能 之四
- Python、C++中编写函数以及不使用临时变量交换两变量值的比较
- 使用Fabric模块编写的批量同步文件的python脚本
- Python使用pygame模块编写俄罗斯方块游戏的代码实例
- 使用Python编写爬虫的基本模块及框架使用指南
- 在python中编写socket服务端模块(一):使用select
- Python中使用urllib2模块编写爬虫的简单上手示例