从 C++ vector 到 Numpy ndarray 的转换非常慢

Conversion from C++ vector to Numpy ndarray is very slow

我将 Boost python 用于程序的计算密集部分,它工作得很好,除了从 C++ 到 python 的数组传递非常慢,反之亦然它是程序整体效率的限制因素。

这里有一个例子来说明我的观点。在 C++ 方面,我 return 一个相对较大的 vector< vector<double> > 类型的矩阵。在 python 方面,我调用该函数并尝试使用两种不同的方法转换生成的数组:numpy.array 方法和我自己的(可能非常天真)基本转换器的 C++ 实现。 C++部分:

#include <boost/python.hpp>
#include <boost/python/numpy.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

using namespace std;

typedef vector<double> vec;
typedef vector<vec> 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<double>();
    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_<vec>("double_vec")
        .def(vector_indexing_suite<vec>())
        ;

    class_<mat>("double_mat")
        .def(vector_indexing_suite<mat>())
        ;

    def("convert_to_numpy", convert_to_numpy);
    def("test", test);
}

python部分:

import test
import numpy as np
import time


def timeit(function):
    def wrapper(*args, **kwargs):
        tb = time.time()
        result = function(*args, **kwargs)
        te = time.time()
        print(te - tb)
        return result
    return wrapper


A = timeit(test.test)()
B = timeit(np.array)(A)
C = timeit(test.convert_to_numpy)(A)

本程序运行结果如下:

0.56
36.68
26.56

转换速度可以更快吗?或者,更好的是,数组可以在 numpy 和 C++ 之间共享。我在谷歌上搜索了很长时间,但没有成功。

这只是部分答案,因为我没有完全理解它起作用的原因,但我发现将转换函数重写为

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);
    p::tuple stride = p::make_tuple(sizeof(double));
    np::dtype dtype = np::dtype::get_builtin<double>();
    p::object own;
    np::ndarray converted = np::zeros(shape, dtype);

    for (u_int i = 0; i < n_rows; i++)
    {
        shape = p::make_tuple(n_cols);
        converted[i] = np::from_data(input[i].data(), dtype, shape, stride, own);
    }
    return converted;
}

显着加快速度。

另一种解决方案是使用 Boost::Multi_array,以确保矩阵连续存储在内存中,从而更快地产生结果。

typedef boost::multi_array<double, 2> c_mat;
np::ndarray convert_to_numpy(c_mat const & input)
{
    u_int n_rows = input.shape()[0];
    u_int n_cols = input.shape()[1];
    p::tuple shape = p::make_tuple(n_rows, n_cols);
    p::tuple strides = p::make_tuple(input.strides()[0]*sizeof(double),
                                     input.strides()[1]*sizeof(double));
    np::dtype dtype = np::dtype::get_builtin<double>();
    p::object own;
    np::ndarray converted = np::from_data(input.data(), dtype, shape, strides, own);
    return converted;
}

我一直以这种方式进行这些转换,它们执行得相当快:

void convert_to_numpy(const mat & input, p::object obj)
{
    PyObject* pobj = obj.ptr();
    Py_buffer pybuf;
    PyObject_GetBuffer(pobj, &pybuf, PyBUF_SIMPLE);
    void *buf = pybuf.buf;
    double *p = (double*)buf;
    Py_XDECREF(pobj);

    u_int n_rows = input.size();
    u_int n_cols = input[0].size();
    for (u_int i = 0; i < n_rows; i++)
    {
        for (u_int j = 0; j < n_cols; j++)
        {
            p[i*n_cols+j] = input[i][j];
        }
    }
}

然后在python:

C = np.empty([10000*10000], dtype=np.float64)
timeit(test.convert_to_numpy)(A,C)

时间安排:

0.557882070541
0.12882900238

我使用 from_data 直接调用 vector.data() 作为源

vector<double>vertices;
auto np_verts= np::from_data(vertices.data(),     // data ->
            np::dtype::get_builtin<double>(),  // dtype -> double
            p::make_tuple(vertices.size()),    // shape -> size
            p::make_tuple(sizeof(double)), p::object());    // stride 1