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 @@
# IVox 近邻与 Point-LIO 观测模型回归
用于验证近邻候选压缩和逐点匹配并行化,直接编译生产头文件、调用实际构建的
`point_lio_component`;不启动雷达、ROS 节点或底盘。需要先完成实车 Point-LIO 构建。
```bash
cd /home/xie/RC2027_BR_code
source /opt/ros/humble/setup.bash
source minco_ws/install/mission/setup.bash
bash minco_ws/docs/diagnostics/ivox_knn_regression/build_and_run.sh \
minco_ws/log/ivox_knn_regression_01
```
脚本从 `minco_ws/build/mission/point_lio/compile_commands.json` 复用生产编译选项,
并链接该构建目录中的 `libpoint_lio_component.so`。不同构建目录可通过
`BR_KNN_COMPILE_COMMANDS=/absolute/path/compile_commands.json` 指定。
输出目录保存实际编译命令、测试程序和 `matching_order.json`。
两个测试分别覆盖:
- `test_ivox_knn.cpp`:646 个随机、空集、少量点、边界及等距用例;与穷举最近距离
以及旧版完整 DistPoint 的 `nth_element` 选择顺序对照。还验证已有候选前缀、点身份,
并报告 10000 次稠密查询耗时和顺序摘要。耗时只作观察,不作为跨机器通过门槛。
- `test_matching_order.cpp`:调用生产 `h_model_input/output`,覆盖两种外参估计开关、
6 种点数及每组 8 次重复,共每种线程模式 192 次观测模型调用。
两个独立进程分别用 `OMP_THREAD_LIMIT=1/4`,比较 Jacobian、残差、掩码及有序近邻的
完整摘要;共 384 次调用。地图每组重建,重复调用也覆盖线程局部候选缓冲的复用。
只对照冻结的旧版头文件时,可设置 `BR_KNN_ONLY=1` 与
`BR_KNN_HEADER_ROOT=/absolute/path/include`,该根目录应包含 `ivox/ivox3d_node.hpp`。
此模式不运行链接组件的观测模型测试,避免旧头文件与新组件混用。
本机最终结果:646 个近邻用例通过;有序近邻摘要 `90192090487253394` 与旧版一致;
单线程/四线程观测模型摘要均为 `1776722514077682147`。
测试限定于本机编译工具链和这些输入,不能据此承诺所有平台、场景的位级一致。
硬件及相同数据回放是独立验证,记录见 [RAIN_NET_005](../../RAIN_NET_005_2026-11-19.md)。
本次证据位于 `minco_ws/log/rain-net-005/`:
`compact_parallel_regression_final.txt`、`compact_parallel/regression_final/`、
`comparison_contract.json`、`compact_parallel/replay_comparison.json`、
`compact_parallel/live_01/summary.json`。回放用原始时间、完整接收并处理至最后一帧,
比较全部里程计和完整点云;该静止记录通过不代表动态或完整任务验收通过。
@@ -0,0 +1,54 @@
#!/usr/bin/env bash
# Directly exercise the production voxel node, without ROS or sensor hardware.
set -euo pipefail
BR_KNN_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
BR_KNN_WS=$(cd -- "$BR_KNN_DIR/../../.." && pwd)
BR_KNN_OUT=${1:-"$BR_KNN_WS/log/ivox_knn_regression"}
mkdir -p -- "$BR_KNN_OUT"
BR_KNN_COMPDB=${BR_KNN_COMPILE_COMMANDS:-"$BR_KNN_WS/build/mission/point_lio/compile_commands.json"}
/usr/bin/python3 - "$BR_KNN_COMPDB" "$BR_KNN_DIR/test_ivox_knn.cpp" "$BR_KNN_OUT" "${BR_KNN_HEADER_ROOT:-}" <<'PY'
import json, os, shlex, subprocess, sys
from pathlib import Path
database, source, output = map(Path, sys.argv[1:4])
if sys.argv[4] and os.environ.get('BR_KNN_ONLY') != '1':
raise SystemExit('BR_KNN_HEADER_ROOT requires BR_KNN_ONLY=1; model tests use the built component')
entry = next(e for e in json.loads(database.read_text()) if e['file'].endswith('laserMapping.cpp'))
args = entry.get('arguments') or shlex.split(entry['command'])
command = [args[0]]
if sys.argv[4]:
command.append('-I' + str(Path(sys.argv[4]).resolve()))
i = 1
while i < len(args):
if args[i] == '-o':
i += 2
continue
if args[i] == '-c' or args[i] == entry['file']:
i += 1
continue
command.append(args[i])
i += 1
base_command = list(command)
command += [str(source.resolve()), '-o', str(output.resolve() / 'test_ivox_knn')]
(output / 'compile_command.json').write_text(json.dumps(command, indent=2) + '\n')
subprocess.run(command, cwd=entry['directory'], check=True)
if os.environ.get('BR_KNN_ONLY') != '1':
component = Path(entry['directory']) / 'libpoint_lio_component.so'
model_binary = output.resolve() / 'test_matching_order'
model_command = base_command + ['-I' + str(Path(entry['file']).parent),
str(source.with_name('test_matching_order.cpp').resolve()),
str(component), '-Wl,-rpath,' + str(component.parent),
'-o', str(model_binary)]
(output / 'model_compile_command.json').write_text(json.dumps(model_command, indent=2) + '\n')
subprocess.run(model_command, cwd=entry['directory'], check=True)
results = []
for limit in ('1', '4'):
result = subprocess.run([str(model_binary)], check=True, text=True, capture_output=True,
env=dict(os.environ, OMP_THREAD_LIMIT=limit))
record = json.loads(result.stdout.strip().splitlines()[-1])
results.append(record)
assert results[0]['matching_digest'] == results[1]['matching_digest'], results
(output / 'matching_order.json').write_text(json.dumps(results, indent=2) + '\n')
print(json.dumps({'serial_parallel_matching': 'PASS', 'cases_per_mode': results[0]['model_cases'],
'digest': results[0]['matching_digest']}))
PY
"$BR_KNN_OUT/test_ivox_knn"
@@ -0,0 +1,126 @@
#include <pcl/point_types.h>
#include "ivox/ivox3d_node.hpp"
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <random>
#include <stdexcept>
#include <unordered_set>
using Point = pcl::PointXYZINormal;
using Node = faster_lio::IVoxNode<Point, 3>;
using Candidate = Node::DistPoint;
std::uint64_t ordered_digest = 1469598103934665603ULL;
void require(bool value, const char * message)
{
if (!value) throw std::runtime_error(message);
}
Point point(float x, float y, float z, int id)
{
Point p{}; p.x=x; p.y=y; p.z=z; p.intensity=id; return p;
}
void check(const std::vector<Point> & points, const Point & query, int k, double range)
{
Node node;
for (const auto & p : points) node.InsertPoint(p);
std::vector<Candidate> selected{Candidate(-7.0, nullptr, -123)};
node.KNNPointByCondition(selected, query, k, range);
require(selected.front().node==nullptr && selected.front().idx==-123 &&
selected.front().dist==-7.0, "earlier voxel candidates changed");
std::vector<double> reference;
std::vector<Candidate> legacy_order;
for (std::size_t index=0;index<points.size();++index) {
const auto & p=points[index];
double d=faster_lio::distance2(p, query);
if (d<range*range) {
reference.push_back(d);
legacy_order.emplace_back(d,&node,static_cast<int>(index));
}
}
// Compatibility oracle: the old implementation partitioned full DistPoints.
// Separately compare against exhaustive distances below, so retaining the old
// permutation cannot hide an incorrect nearest-neighbor result.
if (legacy_order.size()>static_cast<std::size_t>(k)) {
std::nth_element(legacy_order.begin(),legacy_order.begin()+k-1,legacy_order.end());
legacy_order.resize(k);
}
std::sort(reference.begin(),reference.end());
reference.resize(std::min(reference.size(),static_cast<std::size_t>(k)));
require(selected.size()==reference.size()+1, "incorrect candidate count");
std::vector<double> actual;
std::unordered_set<int> ids;
for (std::size_t i=1;i<selected.size();++i) {
const auto & c=selected[i];
require(c.node==&node && c.idx>=0 && c.idx<static_cast<int>(points.size()),
"invalid candidate identity");
require(c.idx==legacy_order[i-1].idx, "legacy candidate order changed");
require(ids.insert(c.idx).second, "candidate duplicated");
require(c.dist==faster_lio::distance2(points[c.idx],query), "candidate distance changed");
ordered_digest^=static_cast<std::uint64_t>(c.idx);
ordered_digest*=1099511628211ULL;
actual.push_back(c.dist);
}
std::sort(actual.begin(),actual.end());
require(actual==reference, "nearest distances differ from exhaustive reference");
}
int main()
{
try {
std::mt19937 random(20261119);
std::uniform_real_distribution<float> coordinate(-2.0F,2.0F);
std::size_t cases=0;
for (int count : {0,1,4,5,6,35,500,2000}) {
std::vector<Point> points;
for (int i=0;i<count;++i) points.push_back(point(coordinate(random),coordinate(random),coordinate(random),i));
for (int k : {1,3,5,10,32}) for (double range : {0.0,0.1,1.0,5.0}) {
for (int repeat=0;repeat<4;++repeat) {
check(points,point(coordinate(random),coordinate(random),coordinate(random),-1),k,range);
++cases;
}
}
}
// Equal-distance candidates and the strict range boundary both matter.
std::vector<Point> tied;
for (int i=0;i<100;++i) tied.push_back(point((i%2) ? 1.F : -1.F,0.F,0.F,i));
tied.push_back(point(0.F,0.F,0.F,100));
for (int k : {1,5,32}) for (double range : {1.0,1.01}) {
check(tied,point(0.F,0.F,0.F,-1),k,range); ++cases;
}
// When fewer than K qualify, preserve the original insertion order.
Node small;
small.InsertPoint(point(3,0,0,0));small.InsertPoint(point(1,0,0,1));
std::vector<Candidate> limited;
small.KNNPointByCondition(limited,point(0,0,0,-1),5,5.0);
require(limited.size()==2 && limited[0].idx==0 && limited[1].idx==1,
"small candidate sequence changed");
// Dense-voxel workload with an order-independent identity digest.
Node dense;
for (int i=0;i<1000;++i) dense.InsertPoint(point(coordinate(random),coordinate(random),coordinate(random),i));
std::vector<Point> queries;
for (int i=0;i<2000;++i) queries.push_back(point(coordinate(random),coordinate(random),coordinate(random),-1));
std::uint64_t digest=1469598103934665603ULL;
auto start=std::chrono::steady_clock::now();
for (int repeat=0;repeat<5;++repeat) for (const auto & q : queries) {
std::vector<Candidate> candidates;
candidates.reserve(35);
dense.KNNPointByCondition(candidates,q,5,5.0);
std::vector<int> ids;
for (const auto & c : candidates) ids.push_back(c.idx);
std::sort(ids.begin(),ids.end());
for (int id : ids) {digest^=static_cast<std::uint64_t>(id);digest*=1099511628211ULL;}
}
double ms=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count();
std::cout<<"{\"status\":\"PASS\",\"reference_cases\":"<<cases
<<",\"dense_queries\":10000,\"dense_ms\":"<<ms
<<",\"ordered_reference_digest\":\""<<ordered_digest<<"\""
<<",\"identity_digest\":\""<<digest<<"\"}\n";
} catch (const std::exception & e) {
std::cerr<<"FAIL: "<<e.what()<<'\n';return 1;
}
}
@@ -0,0 +1,67 @@
// Call the production input/output observation models with fresh deterministic maps.
#include "Estimator.h"
#include <omp.h>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <stdexcept>
std::uint64_t digest = 1469598103934665603ULL;
template<typename T> void hash_value(const T & value)
{
unsigned char bytes[sizeof(T)];std::memcpy(bytes,&value,sizeof(T));
for (auto byte : bytes) {digest^=byte;digest*=1099511628211ULL;}
}
int main()
{
try {
std::size_t cases=0;
for (bool input : {false,true}) for (bool extrinsic : {false,true}) {
use_imu_as_input=input;extrinsic_est_en=extrinsic;
Lidar_R_wrt_IMU.setIdentity();Lidar_T_wrt_IMU<<.01,.02,.03;
kf_input.x_.rot=M3D::Identity();kf_output.x_.rot=M3D::Identity();
kf_input.x_.pos=V3D::Zero();kf_output.x_.pos=V3D::Zero();
kf_input.x_.offset_R_L_I=M3D::Identity();kf_output.x_.offset_R_L_I=M3D::Identity();
kf_input.x_.offset_T_L_I=Lidar_T_wrt_IMU;kf_output.x_.offset_T_L_I=Lidar_T_wrt_IMU;
IVoxType::Options options;options.resolution_=2.F;options.point_resolution_=.1F;
ivox_=std::make_shared<IVoxType>(options);
PointVector map;
for (int x=-25;x<=25;++x) for (int y=-25;y<=25;++y) {
PointType body{};body.x=x*.12F;body.y=y*.12F;body.z=1.5F;body.intensity=map.size();
PointType world{};pointBodyToWorld(&body,&world);map.push_back(world);
}
ivox_->AddPoints(map);laser_point_cov=.01;plane_thr=.1;match_s=81.;
for (int count : {1,5,29,30,200,1000}) {
k=0;idx=-1;time_seq={count};feats_down_body->resize(count);feats_down_world->resize(count);
pbody_list.resize(count);crossmat_list.resize(count);Nearest_Points.resize(count);
for (int j=0;j<count;++j) {
auto & p=feats_down_body->points[j];p.x=-2.F+.013F*(j%307);p.y=-2.F+.017F*((j*17)%233);p.z=1.5F+.001F*(j%3);
pbody_list[j]=V3D(p.x,p.y,p.z);
crossmat_list[j]<<0.,-p.z,p.y,p.z,0.,-p.x,-p.y,p.x,0.;
}
// Repeat to exercise reusable per-worker scratch buffers.
for (int repeat=0;repeat<8;++repeat) {
esekfom::dyn_share_modified<double> model;model.valid=true;
if (input) h_model_input(kf_input.x_,M3D::Identity(),M3D::Identity(),model);
else h_model_output(kf_output.x_,M3D::Identity(),M3D::Identity(),model);
if (!model.valid || !model.h_x.allFinite() || !model.z.allFinite())
throw std::runtime_error("invalid observation model");
hash_value(model.h_x.rows());hash_value(model.h_x.cols());
for (Eigen::Index i=0;i<model.h_x.size();++i) hash_value(model.h_x.data()[i]);
for (Eigen::Index i=0;i<model.z.size();++i) hash_value(model.z.data()[i]);
for (int j=0;j<count;++j) {
hash_value(point_selected_surf[j]);
for (const auto & near : Nearest_Points[j]) {
hash_value(near.x);hash_value(near.y);hash_value(near.z);
}
}
++cases;
}
}
}
std::cout<<"{\"status\":\"PASS\",\"model_cases\":"<<cases
<<",\"matching_digest\":\""<<digest<<"\",\"thread_limit\":"
<<omp_get_thread_limit()<<"}\n";
} catch (const std::exception & e) {std::cerr<<e.what()<<'\n';return 1;}
}
@@ -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
@@ -216,69 +216,40 @@ template <typename PointT, int dim>
int IVoxNode<PointT, dim>::KNNPointByCondition(
std::vector<DistPoint> & dis_points, const PointT & point, const int & K, const double & max_range)
{
std::size_t old_size = dis_points.size();
// #define INNER_TIMER
#ifdef INNER_TIMER
static std::unordered_map<std::string, std::vector<int64_t>> stats;
if (stats.empty()) {
stats["dis"] = std::vector<int64_t>();
stats["put"] = std::vector<int64_t>();
stats["nth"] = std::vector<int64_t>();
const std::size_t old_size = dis_points.size();
if (K <= 0) {
return static_cast<int>(old_size);
}
#endif
for (const auto & pt : points_) {
#ifdef INNER_TIMER
auto t0 = std::chrono::high_resolution_clock::now();
#endif
double d = distance2(pt, point);
#ifdef INNER_TIMER
auto t1 = std::chrono::high_resolution_clock::now();
#endif
if (d < max_range * max_range) {
dis_points.template emplace_back(DistPoint(d, this, &pt - points_.data()));
}
#ifdef INNER_TIMER
auto t2 = std::chrono::high_resolution_clock::now();
auto dis = std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count();
stats["dis"].emplace_back(dis);
auto put = std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count();
stats["put"].emplace_back(put);
#endif
}
#ifdef INNER_TIMER
auto t1 = std::chrono::high_resolution_clock::now();
#endif
// sort by distance
if (old_size + K >= dis_points.size()) {
} else {
std::nth_element(
dis_points.begin() + old_size, dis_points.begin() + old_size + K - 1, dis_points.end());
dis_points.resize(old_size + K);
}
#ifdef INNER_TIMER
auto t2 = std::chrono::high_resolution_clock::now();
auto nth = std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count();
stats["nth"].emplace_back(nth);
constexpr int STAT_PERIOD = 100000;
if (!stats["nth"].empty() && stats["nth"].size() % STAT_PERIOD == 0) {
for (auto & it : stats) {
const std::string & key = it.first;
std::vector<int64_t> & stat = it.second;
int64_t sum_ = std::accumulate(stat.begin(), stat.end(), 0);
int64_t num_ = stat.size();
stat.clear();
std::cout << "inner_" << key << "(ns): sum=" << sum_ << " num=" << num_
<< " ave=" << 1.0 * sum_ / num_ << " ave*n=" << 1.0 * sum_ / STAT_PERIOD << '\n';
// distance2 computes a float squared norm before returning double. Keeping
// that exact value plus its point index avoids materializing a node pointer
// for every candidate. Preserve the legacy partition/comparison order,
// including ties: plane fitting consumes the returned point sequence.
struct LocalCandidate
{
float dist;
int index;
bool operator<(const LocalCandidate & other) const { return dist < other.dist; }
};
thread_local std::vector<LocalCandidate> local_candidates;
local_candidates.clear();
const double range_squared = max_range * max_range;
for (std::size_t index = 0; index < points_.size(); ++index) {
const double d = distance2(points_[index], point);
if (d < range_squared) {
local_candidates.push_back({static_cast<float>(d), static_cast<int>(index)});
}
}
#endif
return dis_points.size();
const std::size_t selected =
std::min(local_candidates.size(), static_cast<std::size_t>(K));
if (local_candidates.size() > selected) {
std::nth_element(local_candidates.begin(), local_candidates.begin() + K - 1,
local_candidates.end());
}
for (std::size_t i = 0; i < selected; ++i) {
const auto & candidate = local_candidates[i];
dis_points.emplace_back(candidate.dist, this, candidate.index);
}
return static_cast<int>(dis_points.size());
}
template <typename PointT, int dim> struct IVoxNodePhc<PointT, dim>::DistPoint
@@ -369,11 +369,17 @@ void h_model_input(state_input & s,
esekfom::dyn_share_modified<double> & ekfom_data)
{
bool match_in_map = false;
VF(4) pabcd;
pabcd.setZero();
normvec->resize(time_seq[k]);
int effect_num_k = 0;
// Each point owns its world point, neighbor vector, mask and plane row.
// The map/state are read-only until this region joins; only the integer
// count is reduced. Assemble Jacobian rows below in the original order.
#ifdef MP_EN
#pragma omp parallel for num_threads(MP_PROC_NUM) reduction(+:effect_num_k) schedule(static)
#endif
for (int j = 0; j < time_seq[k]; j++) {
VF(4) pabcd;
pabcd.setZero();
PointType & point_body_j = feats_down_body->points[idx + j + 1];
PointType & point_world_j = feats_down_world->points[idx + j + 1];
pointBodyToWorld(&point_body_j, &point_world_j);
@@ -475,11 +481,17 @@ void h_model_output(state_output & s,
esekfom::dyn_share_modified<double> & ekfom_data)
{
bool match_in_map = false;
VF(4) pabcd;
pabcd.setZero();
normvec->resize(time_seq[k]);
int effect_num_k = 0;
// Each point owns its world point, neighbor vector, mask and plane row.
// The map/state are read-only until this region joins; only the integer
// count is reduced. Assemble Jacobian rows below in the original order.
#ifdef MP_EN
#pragma omp parallel for num_threads(MP_PROC_NUM) reduction(+:effect_num_k) schedule(static)
#endif
for (int j = 0; j < time_seq[k]; j++) {
VF(4) pabcd;
pabcd.setZero();
PointType & point_body_j = feats_down_body->points[idx + j + 1];
PointType & point_world_j = feats_down_world->points[idx + j + 1];
pointBodyToWorld(&point_body_j, &point_world_j);