サブプロセスPythonモジュールを使用してC++プログラムに繰り返し計算を委託して、Pythonプログラムをスピードアップしようとしています。サブプロセスを使用したPythonとC++プログラム間の通信が非常に遅い
私の問題を説明するために、入力の倍数を返す単純なC++コードを使用しました。数百万の整数に対しては16秒かかるが、これは非常に遅い。ここで
C++プログラム(double.exe)です:
#include <iostream>
using namespace std;
int main()
{
int a;
bool goon = true;
while (goon)
{
cin >> a;
cout << 2 * a << endl;
if (a == 0)
goon= false;
}
}
そしてここではPython 3のコード:通信する
from time import time
from subprocess import PIPE,Popen
cmd = ["double"]
process = Popen(cmd, stdin=PIPE,stdout=PIPE, bufsize=32,universal_newlines=True, shell=True)
t0 = time()
for i in range(1,int(1e6)):
print(i, file=process.stdin, flush=True)
output = int(process.stdout.readline())
dt = time() - t0
print("Time to communicate : %fs" % dt)
print(0,file=process.stdin,flush=True) # close 'double' program
時間:16.029137s
私にとって、遅い理由は、PythonプロセスとC++ progra私はそれを加速する方法を見つけていません。サブプロセスや他のライブラリを使用して、この通信を高速化するソリューションはありますか?
私はWindowsでPython 3.5.2を使用しています。
C++コードをPythonにboost :: pythonのようなモジュールとして公開してみませんか? –
a)ちょうどプロセスの開始と終了にかなりの時間がかかります。b)あなたの計算が実際にはC++でかなり高速かどうかはわかりません。あなたはそれをプロファイリングしましたか? – user45891
モジュールアプローチに加えて、[scipy.weave](https://docs.scipy.org/doc/scipy/reference/weave.html)や[cffi](http:// cffi。 readthedocs.io/en/latest/index.html)(あなたのユースケースに適しているかもしれません)。 – UnholySheep