如何使用C++的字节码优化初始化嵌入式 Python 解释器
How can I initialize an embedded Python interpreter with bytecode optimization from C++?
我正在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 ... */
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 内联映射初始化的动态atexit析构函数崩溃
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 没有用于初始化C++中的变量模板的匹配构造函数
- 在未初始化映射的情况下,将值插入到映射的映射中
- C++成员初始化
- 为什么在C++中首先初始化成员类
- 同时具有"聚合初始化"和"模板推导"
- 初始化具有非默认构造函数的std::数组项的更好方法
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 结构数组的嵌入式C++静态初始化
- 嵌入式 C++:在 C++ 中初始化易失性类型结构
- 如何使用C++的字节码优化初始化嵌入式 Python 解释器
- 在运行时创建Python3模块,同时初始化嵌入式Python
- 嵌入式 Python:Py_Initialize:无法初始化系统标准流