至此,我们就要进入Taichi程序编译的真正底层核心,c++部分了。这里给大家介绍一些调试这种pybind程序的方法,在linux下面可以直接使用gdb对python程序进行调试:
gdb python example.py
如果想使用IDE进行调试的话,可以选择vscode或者clion这两个跨平台的IDE,在linux调试工具同样可以选择gdb,在windows下我们可以使用cppvsgdb,下面给出一个示例launch.json文件
{
"name": "c++ run",
"type": "cppvsdbg",
"request": "launch",
// python interpreter path
"program": "C:/ProgramData/Anaconda3/envs/taichi/python.exe",
"args": [
// python script to run
"${workspaceFolder}/../example/example.py"
],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"console": "externalTerminal",
"env": {
"PYTHONPATH": "${workspaceFolder};${workspaceFolder}/../example"
}
}
如果觉得vscode的调试功能有限可以使用Clion来进行调试,开启调试的时候我们需要在taichi源码的cmake文件上加上调试配置
set(CMAKE_CXX_FLAGS "-g -O0")
之后重新编译,新增一个CMake Application target:
Program 参数设定为待执行的python测试文件,可执行程序为调试Python.exe,选中当前文件夹为工作空间。完成上面的设置我们就可以开始愉快的调试了,让我们回到之前调用Kernel中:
void Kernel::operator()(LaunchContextBuilder &ctx_builder) {
if (!compiled_) {
compile();
}
compiled_(ctx_builder.get_context());
program->sync = (program->sync && arch_is_cpu(arch));
// Note that Kernel::arch may be different from program.config.arch
if (program->this_thread_config().debug &&
(arch_is_cpu(program->this_thread_config().arch) ||
program->this_thread_config().arch == Arch::cuda)) {
program->check_runtime_error();
}
}
我们直接来看到调用Kernel会执行什么,Kernel重载了调用操作符,当调用时会对当前的kernel进行编译,所以在此处我们终于看到了compile这个函数,总算是进入了真正的编译步骤了。