您的位置:首页 > 编程语言 > C语言/C++

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