ctypes是传统的加速方式,先用c++或者c将代码编译为动态库,由ctypes来进行调用。
c++样例代码 count.cc
#include <iostream>
#include<iomanip>
#include<time.h>
using namespace std;
extern "C" int count(int n){
int ans = 0;
for( int i = 0; i <= n; i+=1 ){
ans = ans + 1;
}
return ans;
}
运行g++ -o count.so -shared -fPIC count.cc -O2 生成动态库
python3调用测试代码
from ctypes import *
ctype_handel = cdll.LoadLibrary("./count.so")
print(ctype_handel.count(c_int(9999)))