gpt4 book ai didi

python - pybind11 以某种方式减慢了 c++ 函数

转载 作者:行者123 更新时间:2023-12-03 07:21:45 25 4
gpt4 key购买 nike

我看到的所有 stackoverflow/github 问题都是关于在编码对象的情况下加速 Python 的函数调用。
但我的问题是关于 pybind11 C++ 模块函数中纯 C++ 函数的工作时间。
我有从本地 C++ 库类加载数据集并调用 train 方法的训练函数:

void runSvm() 
// read smvlight file into required sparse representation
auto problem = read_problem( "random4000x20.train.svml" );

CSvmBinaryClassifierBuilder::CParams params( CSvmKernel::KT_Linear );
params.Degree = 3;
params.Gamma = 1/20;
params.Coeff0 = 0;

// measure time here
using namespace std::chrono;
system_clock::time_point startTime = high_resolution_clock::now();

CSvmBinaryClassifierBuilder( params ).Train( *problem ); // measure time only for this line

nanoseconds delay = duration_cast<nanoseconds>( high_resolution_clock::now() - startTime );
std::cout << setprecision(3) << delay / 1e6 << std::endl;
}
我通过 pybind11 将此函数绑定(bind)到 Python:
PYBIND11_MODULE(PythonWrapper, m) {
m.def( "runSvm", &runSvm );
}
然后编译 pybind11 模块库并从 Python 中调用它。定时器值超过 3000ms。
但是当我从纯 C++ 调用这个函数时,定时器的值大约是 800 毫秒。
当然,我期待一些开销,但不是在这个地方,也不是那么多。
我在一个线程中运行它,两种情况下它都 100% 加载了一个内核。
问题可能出在哪里?谁面临同样的问题,你是如何处理的?

最佳答案

当我研究一个可重现的示例时,我发现我在 C++ 示例中比较了不同的 svm 内核(它基于 libsvm 参数证明为“rbf”)和 pybind11 lib(它是硬编码的“线性”)。在修复它并比较相同的算法之后,时间没有差异。

关于python - pybind11 以某种方式减慢了 c++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64893108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com