我使用Boost Python来计算程序的计算密集型部分,它工作得很好,除了将数组从C++传递到Python,反之亦然也很慢,这是程序整体效率的限制因素。在
这里有一个例子来说明我的观点。在C++侧,我返回一个具有较大大小的类型^ {< CD1> }的矩阵。在Python端,我调用该函数并尝试使用两种不同的方法:使用“{{CD2}”方法和我自己(可能是非常天真的)C++实现一个基本转换器来转换结果数组。C++部分:#include
#include
#include
using namespace std;
typedef vector vec;
typedef vector mat;
mat test()
{
int n = 1e4;
mat result(n, vec(n, 0.));
return result;
}
namespace p = boost::python;
namespace np = boost::python::numpy;
np::ndarray convert_to_numpy(mat const & input)
{
u_int n_rows = input.size();
u_int n_cols = input[0].size();
p::tuple shape = p::make_tuple(n_rows, n_cols);
np::dtype dtype = np::dtype::get_builtin();
np::ndarray converted = np::zeros(shape, dtype);
for (u_int i = 0; i < n_rows; i++)
{
for (u_int j = 0; j < n_cols; j++)
{
converted[i][j] = input[i][j];
}
}
return converted;
}
BOOST_PYTHON_MODULE(hermite_cpp)
{
using namespace boost::python;
// Initialize numpy
Py_Initialize();
boost::python::numpy::initialize();
class_("double_vec")
.def(vector_indexing_suite())
;
class_("double_mat")
.def(vector_indexing_suite())
;
def("convert_to_numpy", convert_to_numpy);
def("test", test);
}
python部分:
^{pr2}$
该项目的结果如下:0.56
36.68
26.56
转换能更快吗?或者,甚至更好的是,数组可以在NUMPY和C++之间共享。我在谷歌上搜索了很长时间,但没有多少成功。在