如何使用C++的字节码优化初始化嵌入式 Python 解释器

How can I initialize an embedded Python interpreter with bytecode optimization from C++?

本文关键字:初始化 嵌入式 Python 解释器 优化 何使用 C++ 字节      更新时间:2023-10-16

我正在C++项目中运行嵌入式Python 2.7解释器,我想尽可能地优化解释器。我想这样做的一种方法是使用 __debug__ 变量禁用我的调试语句。我还想实现由于运行带有字节码优化(即-O标志)的 Python 而可能提高的性能。

这个堆栈溢出问题解决了__debug__变量的使用,并指出可以通过运行带有-O的Python来关闭它。但是,对于使用C++钩子创建的嵌入式解释器,显然不能传递此标志。

下面是我的嵌入式解释器初始化代码。该代码不是孤立运行的,但应该提供对我正在使用的环境的一瞥。有没有办法可以更改或添加这些函数调用以指定嵌入式解释器应应用字节码优化,将__debug__变量设置为 False ,并且通常以"发布"模式而不是"调试"模式运行?

void PythonInterface::GlobalInit() {
  if(GLOBAL_INITIALIZED) return;
  PY_MUTEX.lock();
  const char *chome = getenv("NAO_HOME");
  const char *cuser = getenv("USER");
  string home = chome ? chome : "", user = cuser ? cuser : "";
  if(user == "nao") {
    std::string scriptPath = "/home/nao/python:";
    std::string swigPath = SWIG_MODULE_DIR ":";
    std::string corePath = "/usr/lib/python2.7:";
    std::string modulePath = "/lib/python2.7";
    setenv("PYTHONPATH", (scriptPath + swigPath + corePath + modulePath).c_str(), 1);
    setenv("PYTHONHOME", "/usr", 1);
  } else {
    std::string scriptPath = home + "/core/python:";
    std::string swigPath = SWIG_MODULE_DIR;
    setenv("PYTHONPATH", (scriptPath + swigPath).c_str(), 1);
  }
  printf("Starting initialization of Python version %sn", Py_GetVersion());
  Py_InitializeEx(0); // InitializeEx(0) turns off signal hooks so ctrl c still works
  GLOBAL_INITIALIZED = true;
  PY_MUTEX.unlock();
}
void PythonInterface::Init(VisionCore* core) {
  GlobalInit();
  PY_MUTEX.lock();
  CORE_MUTEX.lock();
  CORE_INSTANCE = core;
  thread_ = Py_NewInterpreter();
  PyRun_SimpleString(
    "import pythonswig_modulen"
    "pythonC = pythonswig_module.PythonInterface().CORE_INSTANCE.interpreter_n"
    "pythonC.is_ok_ = Falsen"
    "from init import *n"
    "init()n"
    "pythonC.is_ok_ = Truen"
  );
  CORE_MUTEX.unlock();
  PY_MUTEX.unlock();
}

我在调用Py_InitializeEx(0)之前通过设置PYTHONOPTIMIZE环境变量来解决此问题:

/* ... snip ... */
setenv("PYTHONOPTIMIZE", "yes", 0);
printf("Starting initialization of Python version %sn", Py_GetVersion());
Py_InitializeEx(0); // InitializeEx(0) turns off signal hooks so ctrl c still works
/* ... snip ... */