RAII结合std::chrono::high_resolution_clock可实现函数级自动计时,通过构造/析构记录进出时间,thread_local避免竞争,统一转为微秒便于阅读;支持调用栈追踪与低开销采样分析。

用 RAII 和时钟 API 实现轻量级函数级计时
最直接的性能分析起点是测量单个函数或代码段的执行耗时。C++11 起,std::chrono::high_resolution_clock 提供纳秒级精度(实际取决于平台),配合 RAII 封装可自动记录进出时间:
关键点:避免手动调用 start/stop,用构造/析构自动完成;用 thread_local 避免多线程竞争;时间单位统一转为微秒或毫秒便于阅读。
示例实现:
class ProfilerScope {
std::string_view name_;
std::chrono::time_point<std::chrono::high_resolution_clock> start_;
static thread_local std::vector<std::pair<std::string_view, long long>> samples_;
<p>public:
explicit ProfilerScope(std::string<em>view n) : name</em>(n), start_(std::chrono::high_resolution_clock::now()) {}
~ProfilerScope() {
auto end = std::chrono::high_resolution_clock::now();
auto us = std::chrono::duration<em>cast<std::chrono::microseconds>(end - start</em>).count();
samples_.emplace<em>back(name</em>, us);
}</p><pre class='brush:php;toolbar:false;'>static void dump() {
for (const auto& [name, us] : samples_) {
printf("%s: %lld μs\n", std::string(name).c_str(), us);
}
samples_.clear();
}登录后复制
};
立即学习“C++免费学习笔记(深入)”;
thread_local std::vector<:p style="color:#f60; text-decoration:underline;" href="https://www.php.cn/zt/17539.html" target="_blank">air<:string>view, long long>> ProfilerScope::samples;
用法:void foo() { ProfilerScope _{"foo"}; /* 业务逻辑 */ }。多次调用后调用 ProfilerScope::dump() 查看各函数耗时。
基于栈的调用关系追踪(Callstack Profiling)
仅知道“foo 耗时 500μs”不够,还需知道它被谁调用、是否在 hot loop 中反复进入。需维护一个线程局部的调用栈:
标签: linux js json svg windows 处理器 工具 mac 栈 ai c++ macos win stre
还木有评论哦,快来抢沙发吧~