Files
ViewDesignEngine/tools/vde_io_bench.cpp
T

589 lines
22 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* @file vde_io_bench.cpp
* @brief 网格/点云文件 IO 微基准(STL 二进制/ASCII、OBJ、PLY 读写吞吐)
*
* 用途:
* - 为 IO 性能优化建立可复现的基线(合成网格 + 真实语料文件);
* - 分解大文件导入各阶段耗时(解析 / 拓扑构建 / B-Rep 转换);
* - 在 CI 外手动运行,输出人读表格或 JSON,便于前后对比。
*
* 用法:
* vde_io_bench [--triangles N] [--formats stl,stl_ascii,obj,ply]
* [--repeat R] [--outdir DIR] [--keep] [--json]
* vde_io_bench --file PATH [--repeat R] [--phases] [--import] [--json]
*
* 示例:
* vde_io_bench --triangles 1000000 --repeat 3 --json
* vde_io_bench --file corpus/stl/2-13智能水壶.stl --import --json
*
* 说明:read_stl/read_obj/read_ply 均先整文件读入再解析,重复测量时文件
* 已在页缓存中,因此测得的毫秒数反映解析/构建吞吐而非磁盘带宽。
*/
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <string>
#include <vector>
#include "vde/brep/format_io.h"
#include "vde/foundation/io_obj.h"
#include "vde/foundation/io_ply.h"
#include "vde/foundation/io_stl.h"
#include "vde/brep/mesh_to_brep.h"
#include "vde/mesh/halfedge_mesh.h"
namespace fs = std::filesystem;
using Clock = std::chrono::steady_clock;
namespace {
struct MeshData {
std::vector<vde::foundation::Point3D> verts;
std::vector<std::array<int, 3>> tris;
};
struct Args {
int triangles = 500000;
std::vector<std::string> formats{"stl", "stl_ascii", "obj", "ply"};
int repeat = 3;
std::string file;
std::string outdir;
bool json = false;
bool keep = false;
bool import = false;
bool phases = false;
bool pointcloud = false;
};
struct Measurement {
std::string format;
std::size_t bytes = 0;
double write_ms = 0.0; ///< 最快一次写入耗时
double read_ms = 0.0; ///< 最快一次读取耗时
std::size_t items = 0; ///< 读到的三角形/面数
bool ok = true;
std::string error;
};
double elapsed_ms(Clock::time_point t0) {
return std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
}
std::string lower(std::string s) {
for (auto& c : s) {
if (c >= 'A' && c <= 'Z') c = static_cast<char>(c - 'A' + 'a');
}
return s;
}
bool ends_with(const std::string& s, const std::string& suffix) {
return s.size() >= suffix.size() &&
s.compare(s.size() - suffix.size(), suffix.size(), suffix) == 0;
}
std::string json_escape(const std::string& s) {
std::string out;
out.reserve(s.size() + 8);
for (unsigned char c : s) {
switch (c) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (c < 0x20) {
char buf[8];
std::snprintf(buf, sizeof(buf), "\\u%04x", c);
out += buf;
} else {
out += static_cast<char>(c);
}
}
}
return out;
}
std::string fmt_double(double v, int precision = 2) {
char buf[64];
std::snprintf(buf, sizeof(buf), "%.*f", precision, v);
return buf;
}
// ── 合成网格:n×n 波面,2*(n-1)^2 个三角形 ─────────────────────
MeshData make_grid_mesh(int target_tris) {
MeshData m;
if (target_tris < 2) target_tris = 2;
const int n = std::max(2, static_cast<int>(std::ceil(std::sqrt(target_tris / 2.0))) + 1);
const double inv = 1.0 / static_cast<double>(n - 1);
m.verts.reserve(static_cast<std::size_t>(n) * n);
for (int y = 0; y < n; ++y) {
for (int x = 0; x < n; ++x) {
const double u = x * inv;
const double v = y * inv;
m.verts.emplace_back(u, v, 0.15 * std::sin(u * 9.0) * std::cos(v * 7.0));
}
}
const std::size_t tri_count = static_cast<std::size_t>(2) * (n - 1) * (n - 1);
m.tris.reserve(tri_count);
for (int y = 0; y < n - 1; ++y) {
for (int x = 0; x < n - 1; ++x) {
const int i0 = y * n + x;
const int i1 = i0 + 1;
const int i2 = i0 + n + 1;
const int i3 = i0 + n;
m.tris.push_back({i0, i1, i2});
m.tris.push_back({i0, i2, i3});
}
}
return m;
}
std::vector<vde::foundation::StlTriangle> to_stl(const MeshData& m) {
std::vector<vde::foundation::StlTriangle> out;
out.reserve(m.tris.size());
for (const auto& t : m.tris) {
const auto& a = m.verts[static_cast<std::size_t>(t[0])];
const auto& b = m.verts[static_cast<std::size_t>(t[1])];
const auto& c = m.verts[static_cast<std::size_t>(t[2])];
const auto n = (b - a).cross(c - a);
const double len = n.norm();
vde::foundation::Vector3D normal = len > 0.0 ? vde::foundation::Vector3D(n / len)
: vde::foundation::Vector3D(0.0, 0.0, 1.0);
out.push_back({normal, a, b, c});
}
return out;
}
vde::foundation::ObjMeshData to_obj(const MeshData& m) {
vde::foundation::ObjMeshData data;
data.vertices = m.verts;
data.faces.reserve(m.tris.size());
for (const auto& t : m.tris) {
data.faces.push_back({t[0], t[1], t[2]});
}
return data;
}
/// 以二进制方式取文件字节数。
///
/// 不用 std::filesystem::file_size:MinGW libstdc++ 会把窄字符串按 UTF-8
/// 解释,中文/本地编码语料路径会抛 filesystem_error(Illegal byte sequence)。
std::size_t file_size_bytes(const std::string& path) {
std::ifstream in(path, std::ios::binary | std::ios::ate);
if (!in) return 0;
const std::streampos end = in.tellg();
return end < 0 ? 0 : static_cast<std::size_t>(end);
}
// ── 测量 ───────────────────────────────────────────────────────
template <typename WriteFn, typename ReadFn>
Measurement bench_roundtrip(const std::string& format, const fs::path& path, int repeat,
WriteFn write_fn, ReadFn read_fn, std::size_t expected_items) {
Measurement m;
m.format = format;
double best_write = std::numeric_limits<double>::max();
double best_read = std::numeric_limits<double>::max();
for (int i = 0; i < repeat; ++i) {
const auto t0 = Clock::now();
const bool ok = write_fn(path);
const double ms = elapsed_ms(t0);
if (!ok) {
m.ok = false;
m.error = "write failed";
return m;
}
best_write = std::min(best_write, ms);
}
m.bytes = file_size_bytes(path.string());
for (int i = 0; i < repeat; ++i) {
const auto t0 = Clock::now();
const std::size_t n = read_fn(path);
const double ms = elapsed_ms(t0);
if (n == 0) {
m.ok = false;
m.error = "read returned no items";
return m;
}
best_read = std::min(best_read, ms);
m.items = n;
}
m.write_ms = best_write;
m.read_ms = best_read;
if (expected_items != 0 && m.items != expected_items) {
m.ok = false;
m.error = "item count mismatch: got " + std::to_string(m.items) + " expected " +
std::to_string(expected_items);
}
return m;
}
double mb_per_sec(std::size_t bytes, double ms) {
if (ms <= 0.0) return 0.0;
return static_cast<double>(bytes) / (1024.0 * 1024.0) / (ms / 1000.0);
}
void print_measurement(const Measurement& m) {
std::cout << std::left << std::setw(10) << m.format << std::right << std::setw(10)
<< m.items << std::setw(12) << fmt_double(static_cast<double>(m.bytes) / (1024.0 * 1024.0))
<< std::setw(12) << fmt_double(m.write_ms) << std::setw(12)
<< fmt_double(mb_per_sec(m.bytes, m.write_ms)) << std::setw(12)
<< fmt_double(m.read_ms) << std::setw(12) << fmt_double(mb_per_sec(m.bytes, m.read_ms))
<< (m.ok ? "" : " FAIL: " + m.error) << "\n";
}
std::string measurement_json(const Measurement& m) {
std::string j = "{\"format\":\"" + json_escape(m.format) + "\"";
j += ",\"items\":" + std::to_string(m.items);
j += ",\"bytes\":" + std::to_string(m.bytes);
j += ",\"write_ms\":" + fmt_double(m.write_ms, 3);
j += ",\"read_ms\":" + fmt_double(m.read_ms, 3);
j += ",\"write_mb_s\":" + fmt_double(mb_per_sec(m.bytes, m.write_ms), 2);
j += ",\"read_mb_s\":" + fmt_double(mb_per_sec(m.bytes, m.read_ms), 2);
j += ",\"ok\":";
j += m.ok ? "true" : "false";
if (!m.error.empty()) j += ",\"error\":\"" + json_escape(m.error) + "\"";
j += "}";
return j;
}
void usage() {
std::cout
<< "vde_io_bench — mesh file IO micro benchmark\n"
"\n"
"Synthetic round-trip:\n"
" vde_io_bench [--triangles N] [--formats stl,stl_ascii,obj,ply] [--repeat R]\n"
" [--outdir DIR] [--keep] [--json]\n"
"\n"
"Real file read (STL/OBJ/PLY):\n"
" vde_io_bench --file PATH [--repeat R] [--phases] [--import] [--json]\n"
"\n"
"Options:\n"
" --triangles N synthetic triangle target (default 500000)\n"
" --formats LIST comma separated: stl,stl_ascii,obj,ply (default all)\n"
" --repeat R repetitions, fastest run reported (default 3)\n"
" --outdir DIR directory for synthetic files (default system temp)\n"
" --keep keep generated synthetic files\n"
" --phases with --file .stl: report parse/build phase breakdown\n"
" --import with --file: also time full import_cad pipeline\n"
" --json machine readable output\n"
" -h, --help this help\n";
}
bool parse_args(int argc, char** argv, Args& a, std::string& err) {
for (int i = 1; i < argc; ++i) {
const std::string arg = argv[i];
auto need_value = [&](const char* name) -> const char* {
if (i + 1 >= argc) {
err = std::string("missing value for ") + name;
return nullptr;
}
return argv[++i];
};
if (arg == "-h" || arg == "--help") {
usage();
std::exit(0);
} else if (arg == "--triangles") {
const char* v = need_value("--triangles");
if (!v) return false;
a.triangles = std::atoi(v);
if (a.triangles <= 0) {
err = "--triangles must be > 0";
return false;
}
} else if (arg == "--formats") {
const char* v = need_value("--formats");
if (!v) return false;
a.formats.clear();
std::string list = v;
std::size_t pos = 0;
while (pos <= list.size()) {
const std::size_t comma = list.find(',', pos);
const std::string item =
list.substr(pos, comma == std::string::npos ? std::string::npos : comma - pos);
if (!item.empty()) a.formats.push_back(lower(item));
if (comma == std::string::npos) break;
pos = comma + 1;
}
if (a.formats.empty()) {
err = "--formats is empty";
return false;
}
} else if (arg == "--repeat") {
const char* v = need_value("--repeat");
if (!v) return false;
a.repeat = std::atoi(v);
if (a.repeat <= 0) {
err = "--repeat must be > 0";
return false;
}
} else if (arg == "--file") {
const char* v = need_value("--file");
if (!v) return false;
a.file = v;
} else if (arg == "--outdir") {
const char* v = need_value("--outdir");
if (!v) return false;
a.outdir = v;
} else if (arg == "--keep") {
a.keep = true;
} else if (arg == "--json") {
a.json = true;
} else if (arg == "--import") {
a.import = true;
} else if (arg == "--phases") {
a.phases = true;
} else {
err = "unknown argument: " + arg;
return false;
}
}
return true;
}
// ── 真实文件读取 ──────────────────────────────────────────────
struct FileReadResult {
std::string format;
double read_ms = 0.0;
std::size_t items = 0;
std::size_t bytes = 0;
bool ok = true;
std::string error;
};
FileReadResult bench_file_read(const std::string& path, int repeat) {
FileReadResult r;
const std::string lower_path = lower(path);
r.bytes = file_size_bytes(path);
double best = std::numeric_limits<double>::max();
for (int i = 0; i < repeat; ++i) {
const auto t0 = Clock::now();
if (ends_with(lower_path, ".stl")) {
r.format = "stl";
const auto tris = vde::foundation::read_stl(path);
r.items = tris.size();
} else if (ends_with(lower_path, ".obj")) {
r.format = "obj";
const auto data = vde::foundation::read_obj(path);
r.items = data.faces.size();
} else if (ends_with(lower_path, ".ply")) {
r.format = "ply";
const auto mesh = vde::foundation::read_ply(path);
r.items = mesh.num_faces();
} else {
r.format = "unknown";
r.ok = false;
r.error = "unsupported extension (expected .stl/.obj/.ply)";
return r;
}
const double ms = elapsed_ms(t0);
if (r.items == 0) {
r.ok = false;
r.error = "read returned no items";
return r;
}
best = std::min(best, ms);
}
r.read_ms = best;
return r;
}
// STL 阶段分解:读取字节 → 解析三角形 → 转顶点/索引 → 建半边网格
void bench_stl_phases(const std::string& path) {
double best_read = std::numeric_limits<double>::max();
double best_soup = std::numeric_limits<double>::max();
double best_build = std::numeric_limits<double>::max();
double best_brep = std::numeric_limits<double>::max();
std::size_t tri_count = 0;
for (int i = 0; i < 3; ++i) {
auto t0 = Clock::now();
const auto tris = vde::foundation::read_stl(path);
best_read = std::min(best_read, elapsed_ms(t0));
tri_count = tris.size();
t0 = Clock::now();
std::vector<vde::foundation::Point3D> verts;
std::vector<std::array<int, 3>> idx;
verts.reserve(tris.size() * 3);
idx.reserve(tris.size());
for (const auto& t : tris) {
const int base = static_cast<int>(verts.size());
verts.push_back(t.v0);
verts.push_back(t.v1);
verts.push_back(t.v2);
idx.push_back({base, base + 1, base + 2});
}
best_soup = std::min(best_soup, elapsed_ms(t0));
t0 = Clock::now();
vde::mesh::HalfedgeMesh mesh;
mesh.build_from_triangles(verts, idx);
best_build = std::min(best_build, elapsed_ms(t0));
t0 = Clock::now();
const auto model = vde::brep::mesh_to_brep_model(mesh);
best_brep = std::min(best_brep, elapsed_ms(t0));
(void)model;
}
std::cout << " parse (read_stl) " << fmt_double(best_read) << " ms\n"
<< " soup (tri->verts/idx) " << fmt_double(best_soup) << " ms\n"
<< " build_from_triangles " << fmt_double(best_build) << " ms\n"
<< " mesh_to_brep_model " << fmt_double(best_brep) << " ms\n"
<< " triangles " << tri_count << "\n";
}
} // namespace
int main(int argc, char** argv) {
Args args;
std::string err;
if (!parse_args(argc, argv, args, err)) {
std::cerr << "vde_io_bench: " << err << "\n";
usage();
return 2;
}
if (!args.file.empty()) {
std::vector<FileReadResult> results{bench_file_read(args.file, args.repeat)};
const FileReadResult& r = results.front();
if (!args.json) {
std::cout << "file: " << args.file << "\n";
if (!r.ok) {
std::cout << " read failed: " << r.error << "\n";
} else {
std::cout << " format " << r.format << ", items " << r.items << ", bytes "
<< r.bytes << "\n"
<< " read " << fmt_double(r.read_ms) << " ms, "
<< fmt_double(mb_per_sec(r.bytes, r.read_ms)) << " MB/s\n";
if (args.phases && r.format == "stl") bench_stl_phases(args.file);
}
}
bool import_ok = true;
double import_ms = 0.0;
int import_bodies = 0;
std::string import_error;
if (args.import) {
const auto t0 = Clock::now();
const auto res = vde::brep::import_cad(args.file);
import_ms = elapsed_ms(t0);
import_ok = res.ok;
import_bodies = static_cast<int>(res.bodies.size());
if (!res.diagnostic.issues.empty()) import_error = res.diagnostic.issues.front().message;
if (!args.json) {
std::cout << " import_cad " << fmt_double(import_ms) << " ms, bodies "
<< import_bodies << ", ok " << (import_ok ? "true" : "false") << "\n";
}
}
if (args.json) {
std::cout << "{\"tool\":\"vde_io_bench\",\"file\":\"" << json_escape(args.file)
<< "\",\"repeat\":" << args.repeat << ",\"read\":{";
std::cout << "\"format\":\"" << json_escape(r.format) << "\",\"items\":" << r.items
<< ",\"bytes\":" << r.bytes << ",\"read_ms\":" << fmt_double(r.read_ms, 3)
<< ",\"read_mb_s\":" << fmt_double(mb_per_sec(r.bytes, r.read_ms), 2)
<< ",\"ok\":" << (r.ok ? "true" : "false");
if (!r.error.empty()) std::cout << ",\"error\":\"" << json_escape(r.error) << "\"";
std::cout << "}";
if (args.import) {
std::cout << ",\"import\":{\"ms\":" << fmt_double(import_ms, 3)
<< ",\"bodies\":" << import_bodies
<< ",\"ok\":" << (import_ok ? "true" : "false");
if (!import_error.empty()) {
std::cout << ",\"first_issue\":\"" << json_escape(import_error) << "\"";
}
std::cout << "}";
}
std::cout << "}\n";
}
return (r.ok && (!args.import || import_ok)) ? 0 : 1;
}
// 合成网格基准
MeshData mesh = make_grid_mesh(args.triangles);
fs::path outdir = args.outdir.empty() ? fs::temp_directory_path() : fs::path(args.outdir);
std::error_code ec;
fs::create_directories(outdir, ec);
std::vector<fs::path> created;
auto file_for = [&](const char* ext) {
fs::path p = outdir / (std::string("vde_io_bench.") + ext);
created.push_back(p);
return p;
};
std::vector<Measurement> measurements;
const auto tris = to_stl(mesh);
for (const auto& fmt : args.formats) {
if (fmt == "stl") {
const fs::path p = file_for("stl");
measurements.push_back(bench_roundtrip(
"stl_bin", p, args.repeat, [&](const fs::path& fp) { return vde::foundation::write_stl(fp.string(), tris); },
[](const fs::path& fp) { return vde::foundation::read_stl(fp.string()).size(); },
tris.size()));
} else if (fmt == "stl_ascii") {
const fs::path p = file_for("ascii.stl");
measurements.push_back(bench_roundtrip(
"stl_ascii", p, args.repeat,
[&](const fs::path& fp) { return vde::foundation::write_stl_ascii(fp.string(), tris); },
[](const fs::path& fp) { return vde::foundation::read_stl(fp.string()).size(); },
tris.size()));
} else if (fmt == "obj") {
const auto obj = to_obj(mesh);
const fs::path p = file_for("obj");
measurements.push_back(bench_roundtrip(
"obj", p, args.repeat,
[&](const fs::path& fp) { return vde::foundation::write_obj(fp.string(), obj); },
[](const fs::path& fp) { return vde::foundation::read_obj(fp.string()).faces.size(); },
obj.faces.size()));
} else if (fmt == "ply") {
vde::mesh::HalfedgeMesh hm;
hm.build_from_triangles(mesh.verts, mesh.tris);
const fs::path p = file_for("ply");
measurements.push_back(bench_roundtrip(
"ply", p, args.repeat,
[&](const fs::path& fp) { return vde::foundation::write_ply(fp.string(), hm); },
[](const fs::path& fp) { return vde::foundation::read_ply(fp.string()).num_faces(); },
hm.num_faces()));
} else {
std::cerr << "vde_io_bench: unknown format: " << fmt << "\n";
return 2;
}
}
if (args.json) {
std::cout << "{\"tool\":\"vde_io_bench\",\"triangles\":" << mesh.tris.size()
<< ",\"repeat\":" << args.repeat << ",\"measurements\":[";
for (std::size_t i = 0; i < measurements.size(); ++i) {
if (i) std::cout << ",";
std::cout << measurement_json(measurements[i]);
}
std::cout << "]}\n";
} else {
std::cout << "synthetic mesh: " << mesh.tris.size() << " triangles\n";
std::cout << std::left << std::setw(10) << "format" << std::right << std::setw(10)
<< "items" << std::setw(12) << "MB" << std::setw(12) << "write_ms"
<< std::setw(12) << "w_MB/s" << std::setw(12) << "read_ms"
<< std::setw(12) << "r_MB/s" << "\n";
for (const auto& m : measurements) print_measurement(m);
}
if (!args.keep) {
for (const auto& p : created) {
fs::remove(p, ec);
}
} else {
std::cout << "files kept in " << outdir.string() << "\n";
}
for (const auto& m : measurements) {
if (!m.ok) return 1;
}
return 0;
}