循环是否需要运行时间C++?

Is it C++ for loop had require run time?

本文关键字:C++ 运行时间 是否 循环      更新时间:2023-10-16

我有一个c++程序,在 for 循环中调用一个函数。
该功能正在做一个繁重的过程,它嵌入了python并执行图像处理。

我的问题是,为什么它只能在变量的第一个实例上运行?

主函数(我只显示此标题中需要的部分代码):

int main(){
for(int a = 0;a<5;a++){
for(int b=0;b<5;b++){
// I want every increment it go to PyRead() function, doing image processing, and compare 
if(PyRead()==1){
// some application might be occur
}
else {
}
}
} 

PyRead()功能,该功能c++进入python环境中执行图像处理:

bool PyRead(){

string data2;
Py_Initialize();    

PyRun_SimpleString("print 'hahahahahawwwwwwwwwwwww' ");
char filename[] = "testcapture";

PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(".")");
PyObject * moduleObj = PyImport_ImportModule(filename);
if (moduleObj)
{
PyRun_SimpleString("print 'hahahahaha' ");
char functionName[] = "test";
PyObject * functionObj = PyObject_GetAttrString(moduleObj, functionName);
if (functionObj)
{
if (PyCallable_Check(functionObj))
{
PyObject * argsObject = PyTuple_New(0);
if (argsObject)
{
PyObject * resultObject = PyEval_CallObject(functionObj, argsObject);
if (resultObject)
{
if ((resultObject != Py_None)&&(PyString_Check(resultObject))) 
{
data2 = PyString_AsString(resultObject);
}
Py_DECREF(resultObject);
}
else if (PyErr_Occurred()) PyErr_Print();
Py_DECREF(argsObject);
}
}
Py_DECREF(functionObj);
}
else PyErr_Clear();
Py_DECREF(moduleObj);
}
Py_Finalize();

std::cout << "The Python test function returned: " << data2<< std::endl;


cout << "Data2 n" << data2;
if(compareID(data2) == 1)
return true;
else 
return false;
} 

这是我第二次在堆栈溢出中问这个问题。希望这次这个问题能更清楚!

我可以成功编译而没有错误。

当我运行程序时,我意识到在a=0b=0它会转到PyRead()函数并返回值,之后它会转到a=0b=1,那一刻整个程序将结束。
它假设再次转到PyRead()函数,但它没有这样做并直接结束程序。

我必须强烈提到PyRead()函数需要很长时间才能运行(30 秒)。

我不知道发生了什么,寻求帮助。请专注于粗体部分以理解我的问题。

谢谢。

请参阅 https://docs.python.org/2/c-api/init.html#c.Py_Finalize 中的评论

理想情况下,这会释放 Python 解释器分配的所有内存。

不会卸载由 Python 加载的动态加载的扩展模块。

如果多次调用某些扩展的初始化例程,则可能无法正常工作

似乎您的模块不能很好地使用此函数。

解决方法可以是 - 动态创建脚本并使用 python 子进程调用它。