gpt4 book ai didi

c++ - 将列表从 python 传递到 C++ vector 时如何加速 Boost::Python::Extract

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:30:31 26 4
gpt4 key购买 nike

我是 boost.python 的新手,并且创建了一个简单的函数来将列表从 python 传递到 C++ vector :

void SetXValues(boost::python::list xl){
int n = len((xl));
xvals.resize(n);
for(unsigned int i=0; i<n; i++){
xvals[i] = boost::python::extract<double>((xl)[i]);
}
}

xvals 是一个 C++ STL vector 。这个函数有效,我可以将 python 列表加载到 C++ 中,但它看起来非常慢。

我做的一个小速度测试是用 C++ 和纯 Python 编写分箱算法。结果表明,如果算上从 Python 传递数据的时间,C++ 方法的速度仅快 5 倍,但当然单独的分箱算法要快得多 (74 倍)。

那么有什么办法可以改进上面的功能,使其更加高效呢?

最佳答案

在性能关键部分,如您所描述的。我通常避免将数据存储在 python list 中首先。 list是在其中存储任意对象的正确数据类型。特别是列表中的每个对象都可以有不同的类型。但是您已经知道这将是一个“ double 列表”。

我建议改为使用 std::vector<double>已经在 python 。为此,您将导出 std::vector<double>作为class_ , 让我们称之为 VectorOfDOubles ,使用 boost python。你可以这样做,在 python 中你不会看到 list 之间的区别。和 VectorOfDoubles ,主要区别在于您将其构建为 xl = VectorOfDoubles(55)而不是 xl = [] .您需要做一些工作才能使 index-acees 正常工作,例如xl[5] = 4.5,但为此存在 boost 索引套件,我推荐版本 2,以帮助您。

另一种选择是使用 numpy ndarrays 而不是 list .存在 boost numpy 库,可帮助您使用来自 boost python 的 numpy ndarrays。

但是正如您所说,您是 boost python 的新手,boost numpy 和 boost indexing suite 都可能有点难。也许您首先想解决创建自己的 std::vector<double> 子类的问题,说 VectorOfDOubles , 并定义 double get(int i)void set(int i, double val)然后将这两个函数(连同 size(),构造函数)导出到 python。这需要对您的 Python 代码进行一些更改,但对于初学者来说更容易。

关于c++ - 将列表从 python 传递到 C++ vector 时如何加速 Boost::Python::Extract,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12929196/

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