perf(Point-LIO): iVox 近邻候选压缩 + 逐点观测模型并行化

两处改动共同针对实车持续计算积压:

1) ivox3d_node.hpp get_removed_points/nearby:候选改为 thread_local 的
   {float dist, int index},不再为每个候选构造节点指针;同时删除 INNER_TIMER
   死代码。刻意保留原有的分组/比较顺序(含平局),因为平面拟合消费的是返回序列,
   顺序变了会改变拟合结果。K<=0 直接返回。

2) Estimator.cpp h_model_input/h_model_output:逐点循环加 OpenMP 并行,
   reduction 只作用于整数计数;pabcd 由循环外移入循环内——这是并行化的前提,
   移出后每个线程各自持有,否则是数据竞争。Jacobian 行仍按原顺序组装。

回归:docs/diagnostics/ivox_knn_regression 直接编译生产头、调用实际构建的
point_lio_component,覆盖近邻压缩与并行两处,不启雷达/节点/底盘。
测量工具:docs/diagnostics/profile_pointlio_latency 复用实车构建生成独立诊断
二进制,只往 laserMapping.cpp 副本插入计时,源码结构漂移时拒绝猜测插入。
This commit is contained in:
walunt5
2026-11-19 16:44:37 +08:00
parent 9fdc34321e
commit b875c71e65
9 changed files with 558 additions and 64 deletions
@@ -0,0 +1,42 @@
# Point-LIO 分段延迟诊断
复用已有实车构建,生成独立原生诊断二进制;不写生产源码、build 对象或 install。
需要当前 Point-LIO 原生程序已完成构建,且源码与其余对象文件一致。
构建器只往 laserMapping.cpp 副本插入计时语句,原算法语句不变;源码结构漂移时拒绝猜测插入。
```bash
cd /home/xie/RC2027_BR_code
source /opt/ros/humble/setup.bash
source minco_ws/install/mission/setup.bash
python3 minco_ws/docs/diagnostics/profile_pointlio_latency/build_profile.py \
--out minco_ws/log/pointlio_latency_build_01
```
输出目录必须不存在。build.json 保留原源码 SHA256、编译/链接命令及阶段编号。
仅替换原生程序的 laserMapping 对象,其余对象、编译选项和库来自现有构建。
在已有独立静止诊断或离线回放中,用输出的 pointlio_mapping 替换程序路径,
参数、输入和环境保持一致,额外给该进程设置:
```bash
export RAIN_LATENCY_TRACE_PATH=/absolute/path/to/new_phase.csv
```
父目录须存在,文件须不存在;缺失或无法独占创建时,明确输出错误并禁用分段记录。
不要运行正式任务入口,不伪造场地确认、里程计或源时间,不启动底盘。
切换诊断程序前应停止上一定位程序,诊断结束用 SIGINT 正常退出。
CSV 每个初始化/处理帧保存 15 个阶段的累计墙钟及处理线程 CPU 时间,
包含预测、观测更新、逐点完整点处理、里程计发布、地图更新及日志等。
编号见 build.json 的 phases。循环内同类阶段跨所有批次累加;
OdomPublish 包含随后的状态日志,FinishScan 包含末帧里程计,Statistics 包含已有 IVox 定期统计。
处理线程 CPU 时间不包含 OpenMP 其他工作线程,不能把两者差值直接当成系统调度等待。
还需结合调用栈、同步、I/O 与线程数据区分阻塞原因。
记录点在 sync_packages 成功之后、循环 rate.sleep 之前,未覆盖外部输入等待。
CSV 写出发生在计时之后;记录仍会改变时序,**不能用插桩程序替代未插桩程序的实时验收**。
monotonic_ns 为单调时钟,不是设备采样时间。既有性能 CSV 的绝对时间列精度有限,
需要精确对齐时使用原始消息纳秒时间和相应记录,不据其低精度值对齐点云。
2026-11-19 的 .110 静止排查见 [RAIN_NET_007](../../RAIN_NET_007_2026-11-19.md)。
当时分段采样未复现前一轮百毫秒级额外停顿,因此没有据此修改生产算法或断言原问题已修复。
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""Build a separate instrumented native executable using the existing build."""
import argparse
import hashlib
import json
from pathlib import Path
import shlex
import shutil
import subprocess
PHASES = ['Startup', 'ImuProcess', 'Enqueue', 'VoxelSort', 'InitMap', 'ModelPrep',
'Predict', 'LidarUpdate', 'FullSegment', 'OdomPublish', 'PointTransform',
'FinishScan', 'MapUpdate', 'EndPublish', 'Statistics']
def instrument(text):
# Match whole existing markers; fail on source drift rather than guess.
markers = [
('if (sync_packages(Measures)) {',
'if (sync_packages(Measures)) {\n rain_latency::Frame rain_profile{static_cast<unsigned long long>(startup_frame_cnt_+1)};', 1),
(' /*** downsample the feature points in a scan ***/',
' rain_profile.next(rain_latency::ImuProcess);\n /*** downsample the feature points in a scan ***/', 1),
(' enqueueFullCloud(feats_undistort, Measures.lidar_beg_time);',
' rain_profile.next(rain_latency::Enqueue);\n enqueueFullCloud(feats_undistort, Measures.lidar_beg_time);', 1),
(' if (space_down_sample) {',
' rain_profile.next(rain_latency::VoxelSort);\n if (space_down_sample) {', 1),
(' if (!p_imu->after_imu_init_)',
' rain_profile.next(rain_latency::InitMap);\n if (!p_imu->after_imu_init_)', 1),
(' /*** ICP and Kalman filter update ***/',
' rain_profile.next(rain_latency::ModelPrep);\n /*** ICP and Kalman filter update ***/', 1),
(' time_current = point_body.curvature / 1000.0 + pcl_beg_time;',
' rain_profile.next(rain_latency::Predict);\n time_current = point_body.curvature / 1000.0 + pcl_beg_time;', 2),
(' const auto update_start = statistics_enabled',
' rain_profile.next(rain_latency::LidarUpdate);\n const auto update_start = statistics_enabled', 2),
(' processFullCloudSegmentWithSnapshot(makeStateSnapshot(time_current));',
' rain_profile.next(rain_latency::FullSegment);\n processFullCloudSegmentWithSnapshot(makeStateSnapshot(time_current));', 2),
(' if (publish_odometry_without_downsample) {',
' rain_profile.next(rain_latency::OdomPublish);\n if (publish_odometry_without_downsample) {', 2),
(' for (int j = 0; j < time_seq[k]; j++) {',
' rain_profile.next(rain_latency::PointTransform);\n for (int j = 0; j < time_seq[k]; j++) {', 2),
(' /******* Publish odometry downsample *******/',
' rain_profile.next(rain_latency::FinishScan);\n /******* Publish odometry downsample *******/', 1),
(' if (feats_down_size > 4) {',
' rain_profile.next(rain_latency::MapUpdate);\n if (feats_down_size > 4) {', 1),
(' /******* Publish points *******/',
' rain_profile.next(rain_latency::EndPublish);\n /******* Publish points *******/', 1),
(' const StateLogRecord state_log = makeStateLogRecord();',
' rain_profile.next(rain_latency::Statistics);\n const StateLogRecord state_log = makeStateLogRecord();', 1),
]
original = text
for before, after, count in markers:
if text.count(before) != count:
raise ValueError('unexpected source layout at ' + before.strip())
text = text.replace(before, after)
# No original algorithm statement may change or move.
reverse = text
for before, after, _ in reversed(markers):
reverse = reverse.replace(after, before)
if reverse != original:
raise ValueError('instrumentation did not preserve original statements')
return '#include "latency_profile.hpp"\n' + text
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--out', type=Path, required=True)
ws = Path(__file__).resolve().parents[3]
parser.add_argument('--compile-commands', type=Path,
default=ws / 'build/mission/point_lio/compile_commands.json')
args = parser.parse_args()
database = json.loads(args.compile_commands.read_text())
entry = next(e for e in database if e['file'].endswith('/laserMapping.cpp') and
any('POINT_LIO_BUILD_MAIN' in x for x in
(e.get('arguments') or shlex.split(e['command']))))
source = Path(entry['file'])
instrumented = instrument(source.read_text())
build = Path(entry['directory'])
output = args.out.resolve()
output.mkdir(parents=True, exist_ok=False)
shutil.copyfile(Path(__file__).with_name('latency_profile.hpp'), output / 'latency_profile.hpp')
(output / 'laserMapping.cpp').write_text(instrumented)
command = list(entry.get('arguments') or shlex.split(entry['command']))
command[command.index('-o') + 1] = str(output / 'laserMapping.cpp.o')
command[command.index('-c') + 1] = str(output / 'laserMapping.cpp')
command.insert(1, '-I' + str(source.parent))
link = shlex.split((build / 'CMakeFiles/pointlio_mapping.dir/link.txt').read_text())
original_object = 'CMakeFiles/pointlio_mapping.dir/src/laserMapping.cpp.o'
if link.count(original_object) != 1:
raise ValueError('unexpected native link layout')
link[link.index('-o') + 1] = str(output / 'pointlio_mapping')
link[link.index(original_object)] = str(output / 'laserMapping.cpp.o')
metadata = {'source': str(source), 'source_sha256': hashlib.sha256(source.read_bytes()).hexdigest(),
'compile': command, 'link': link, 'phases': PHASES,
'scope': 'Independent profiling executable; original source/build/install not written'}
(output / 'build.json').write_text(json.dumps(metadata, indent=2) + '\n')
subprocess.run(command, cwd=build, check=True)
subprocess.run(link, cwd=build, check=True)
print(output / 'pointlio_mapping')
if __name__ == '__main__':
main()
@@ -0,0 +1,77 @@
#pragma once
#include <array>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <ctime>
namespace rain_latency {
enum Phase {
Startup, ImuProcess, Enqueue, VoxelSort, InitMap, ModelPrep, Predict,
LidarUpdate, FullSegment, OdomPublish, PointTransform, FinishScan, MapUpdate,
EndPublish, Statistics, Count
};
inline long long wall_ns()
{
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
}
inline long long cpu_ns()
{
timespec t{};
clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t);
return t.tv_sec * 1000000000LL + t.tv_nsec;
}
struct TraceOutput {
FILE * file = nullptr;
TraceOutput()
{
const char * path = std::getenv("RAIN_LATENCY_TRACE_PATH");
if (path) {
// A diagnostic must never overwrite a previous run.
file = std::fopen(path, "wx");
}
if (!file) {
std::fputs("[latency profile] Set RAIN_LATENCY_TRACE_PATH to a new writable file; trace disabled\n", stderr);
return;
}
std::fputs("frame,monotonic_ns,phase,wall_ms,thread_cpu_ms\n", file);
}
~TraceOutput() { if (file) std::fclose(file); }
};
struct Frame {
unsigned long long id;
Phase phase = Startup;
long long wall = wall_ns(), cpu = cpu_ns();
std::array<long long, Count> walls{}, cpus{};
void next(Phase p)
{
const auto w = wall_ns(), c = cpu_ns();
walls[phase] += w - wall;
cpus[phase] += c - cpu;
wall = w;
cpu = c;
phase = p;
}
~Frame()
{
next(Statistics);
static TraceOutput output;
if (!output.file) return;
for (int i = 0; i < Count; ++i) {
std::fprintf(output.file, "%llu,%lld,%d,%.12g,%.12g\n",
id, wall, i, walls[i] * 1e-6, cpus[i] * 1e-6);
}
if (id % 20 == 0) std::fflush(output.file);
}
};
} // namespace rain_latency