场景
假设有一个高计算场景:双层循环,复杂度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()