繁体   English   中英

C++ 优化循环和 if 语句

[英]C++ Optimizing for loops and if statements

我正在尝试优化一个过滤脚本,该脚本接收大量激光雷达点(约 1.75 亿)并根据它们是否落在特定范围内(x 最小最大值、y 最小值最大值和 z 最小值最大值)来过滤它们。

现在脚本遍历每个点,然后遍历每个边界条件(有多个边界),然后在 if 语句中测试它是否落在这些边界内。 (见代码)

namespace filtering{
    std::vector<points_by_roof> filter_by_roof (std::vector<pointcloud::xyzfloats>& coordinates, const std::vector<roof_bounds>& bounds){
        //create filtered structure - roof_id, vector with all coordinates that will fall in that slice
        std::vector<points_by_roof> filtered (bounds.size());
        for (int i=0; i < bounds.size(); i++){
            filtered[i].id = bounds[i].id;
        }
        //Filtering points by roof slice
        for (int i=0; i < coordinates.size(); i++){
            for (int j=0; j < bounds.size(); j++){
                if (coordinates[i].z > bounds[j].z_range[0] && coordinates[i].z < bounds[j].z_range[1] &&
                    coordinates[i].x > bounds[j].x_range[0] && coordinates[i].x < bounds[j].x_range[1] &&
                    coordinates[i].y > bounds[j].y_range[0] && coordinates[i].y < bounds[j].y_range[1]){
                    
                    filtered[j].points.push_back({coordinates[i].x, coordinates[i].y, coordinates[i].z});

                    break;
                }
            }
        }
        return filtered;
    }
}  

该代码在大约 20 秒内运行了 1.75 亿个点。 一旦我切换 if 语句以首先运行“z”边界,它下降到大约 17 秒。

我知道 C++ 在它改变的地方所做的 if 语句优化:

if (a==b && c==d){} 

if (a==b) {
    if (c==d){}
}

但我认为更改首先要测试的“z”边界是这种优化类型的唯一可靠示例。 有没有办法更快地运行这个?

(感觉 for 循环真的会影响时间,但我对 C++ 也很陌生,所以我可能不正确)

任何帮助将不胜感激,谢谢:)。


编辑:

我很抱歉缺少代码和规范,我现在看到它不是很容易提供帮助(我是 C++ 新手)。

对于下面的评论 - 不应该有落在两个盒子里的点。

整个项目 - 从 a.las 文件(激光雷达点云文件)中读取点,过滤到框(定义屋顶的一部分),并(对于每个框)拟合最佳拟合平面并计算厚度屋顶。

以下是正在使用的数据类型:

在命名空间点云中(在 point_cloud.h 中)

struct xyzfloats {
    float x, y, z;
    xyzfloats(float x_val, float y_val, float z_val) : x(x_val), y(y_val), z(z_val){}
};

在命名空间过滤中(在 filtering.h 中)

struct points_by_roof {
    std::string id;
    std::vector<pointcloud::xyzfloats> points;
};

struct roof_bounds {
    std::string id;
    int x_range[2], y_range[2], z_range[2];
};

我对 C++ 和 C++ 优化非常陌生,因此对不同数据类型或函数的任何解释(及其差异)都会有所帮助。

如果有帮助,我可以添加更多(或全部)我的代码。 我不能(作为对评论的回应)将 a.las 文件上传到堆栈溢出。

你写if的方式几乎没有重要性。 编译器可以处理它。

最明显的问题是push_back 请务必先reserve ,以防止分配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM