避免在共享库之间传递数据的开销

时间:2019-05-11 07:46:34

标签: c++ qt

第一个共享库中,用于3D坐标的数据以Point结构存储:

struct Point {

    float x{0}, y{0}, z{0};

};

std::vector<Point> *m_points;

第二个共享库中,用于3D坐标的数据与PointContainer类一起存储

class PointContainer : public QObject
{
    Q_OBJECT

    // This is a sophisticated class ...

public:
    QVector3D m_coord;
}

QVector<PointContainer> *m_points;

要将数据从 2 个共享库传递到 1 一个,我正在使用循环:

std::vector<Point> data(number_of_points);
// Prepare the data in the structure needed by the 1st shared library
    for (size_t i = 0; i < number_of_points; ++i) {
        float x = m_points->at(i).m_coord.x();
        float y = m_points->at(i).m_coord.y();
        float z = m_points->at(i).m_coord.z();
        Point point = {};
        point.x = x;
        point.y = y;
        point.z = z;
        data[i] = point;
    }
// Now pass data to the 1st shared library

number_of_points可能很大,并且上述循环可能在计算上很昂贵。有什么方法可以避免上述循环?我试图在共享库中以相同的结构存储数据,但是这需要对代码进行大量修改。不确定是否还有其他选择,只需询问即可。

1 个答案:

答案 0 :(得分:1)

此代码将更简洁一些,并且速度更快:

std::vector<Point> data(number_of_points);
// Prepare the data in the structure needed by the 1st shared library
for (size_t i = 0; i < number_of_points; ++i) {
    const auto& source = (*m_points)[i].m_coord;
    data[i] = {source.x(), source.y(), source.z()};
}
// Now pass data to the 1st shared library

如果您的点数至少为 几千万,则可以使用OpenMP或Intel TBB的parallel_for加快该循环。

相关问题