使用C ++进行缓慢的Matlab R2018b TypedArray数组访问

时间:2018-11-05 19:59:16

标签: c++ arrays matlab

我正在使用MATLAB R2018b mex函数将C ++库与我的MATLAB代码集成在一起。作为其中的一部分,我需要将数据保存在MATLAB数组中,并保存到C ++指针数组和C ++结构向量中。但是,映射matlab类型的数组被证明非常慢(对于〜800,000个元素,约为0.4秒)。

这是相关代码

const matlab::data::TypedArray<float> Vertices = std::move(inputs[0]); 
float* positions = new float[Vertices.getNumberofElements()];
for (size_t i = 0; i < Vertices.getDimensions()[0]; i ++)
{
    ctr = 9 * i;
    positions[ctr + 0] = Vertices[i][0];
    positions[ctr + 1] = Vertices[i][1];
    positions[ctr + 2] = Vertices[i][2]; 
}

是什么导致此循环变慢?我尝试为Vertices重新排序数组访问,以尝试使代码对缓存更友好,但这并没有产生有意义的加速。现在,对于80万个元素,循环约为0.4ms,理想情况下,内存复制应该花费更少的时间,对吗?

当我查看以前的建议时,我发现大多数答案都使用较旧的mex函数,而new(?)MATLAB C ++ API不具有相同的函数或结构。

编辑:

我遵循了Cris的建议,并在迭代器上进行了循环,从而将速度提高了一半,达到0.14秒。

我正在使用的新代码是:

    const matlab::data::TypedArray<float> Vertices = std::move(inputs[0]); 
    float* positions = new float[Vertices.getNumberofElements()];
for (auto it = Vertices.begin(); it != Vertices.end(); ++it)
{
    positions[ctr] = *it; 
    ++ctr; 
} 

因此它更快,但仍然出奇的慢(800,000个元素需要0.14秒)。还有其他方法可以加快此循环吗?

1 个答案:

答案 0 :(得分:2)

通过应用Cris建议并使用以下代码,我得到了极大的提速:

const matlab::data::TypedArray<float> Vertices = std::move(inputs[0]);
float* positions = new float[Vertices.getNumberofElements()];
memcpy(positions,&*Vertices.begin,sizeof(float)*Vertices.getNumberofElements());

运行时从0.14(使用标准Visual Studio优化)变为0.0035,对于我的应用程序来说,这是可以接受的快速速度。

相关问题