我有一个python程序,它生成一个数学表达式,如
exp(sin(x-y))**2现在我想把它给我的C++程序,它必须用不同的x,y值来计算这个表达式。我的第一种方法是在PyRun_String中使用Python.h库。
在这里,初始化代码:
func=function;
Py_Initialize();
memset(pythonString,0,strlen(pythonString));
// add whiteNoise Kernel
sprintf(pythonString,"from math import *;func=lambda x,y:(%s+0.1*(x==y))",function);
//printf("%s\n",pythonString);
PyRun_SimpleString(pythonString);在这里,需要多次评估的代码:
char execString[200];
memset(execString,0,strlen(execString));
sprintf(execString,"result=func(%f,%f)",x1[0], x2[0]);
PyObject* main = PyImport_AddModule("__main__");
PyObject* globalDictionary = PyModule_GetDict(main);
PyObject* localDictionary = PyDict_New();
//create the dictionaries as shown above
PyRun_String(execString, Py_file_input, globalDictionary, localDictionary);
double result = PyFloat_AsDouble(PyDict_GetItemString(localDictionary, "result"));但是,我认为每次用PyRun_String解析字符串实在太慢了。是否有一种方法可以直接将Python表达式转换为C++函数,从而可以有效地调用?还是有别的选择?使用像symbolicc++这样的东西也是可以的
发布于 2015-06-26 17:02:20
我建议将所有输入作为数组/向量传递给您的c++ &立即解决所有问题。另外,尝试Py_CompileString & PyEval_EvalCode而不是PyRun_String。我不得不解决数以百万计的方程式,发现速度提高了10倍。
下面是一个简单的'a + b'的例子,但是对于更多的for循环,我们可以将它推广到任意变量的任何方程。在我的机器上,下面的百万个值在不到1秒钟的时间内就完成了(而对于PyRun_String,则是10秒)。
PyObject* main = PyImport_AddModule("__main__");
PyObject* globalDict = PyModule_GetDict(main);
PyCodeObject* code = (PyCodeObject*) Py_CompileString("a + b", "My Eqn", Py_eval_input);
for (millions of values in input) {
PyObject* localDict = PyDict_New();
PyObject* oA = PyFloat_FromDouble(a); // 'a' from input
PyObject* oB = PyFloat_FromDouble(b); // 'b' from input
PyDict_SetItemString(localDict, "a", oA);
PyDict_SetItemString(localDict, "b", oB);
PyObject* pyRes = PyEval_EvalCode(code, globalDict, localDict);
r = PyFloat_AsDouble(pyRes);
// put r in output array
Py_DECREF(pyRes);
Py_DECREF(localDict)
}
Py_DECREF(code);https://stackoverflow.com/questions/30507347
复制相似问题