9.1 性能剖析器
OGRE 的 Profiler(OgreProfiler.h/.cpp)是一棵按名字组织的层次计时树。它以 beginProfile("Culling") / endProfile("Culling") 成对调用围住一段代码,把耗时记录到对应节点;同一名字在不同帧反复出现,节点复用但统计按帧号刷新。这套机制与常见的「打点累计耗时」的区别在于:父节点时间并不直接等于「总帧时间减去子节点之和」,而是逐层用 accum 排除子耗时,从而精确反映「父自身花费」。
本章与站内既有内容的分工
8.3 讨论的是渲染状态缓存与后端能力分级;本节进入运行期性能观测工具链。卷一至卷三讲的是「引擎怎么画」,本节与 9.2、9.3 一起讲「引擎怎么慢、怎么量化、怎么优化」:9.1 是计时树,9.2 是渲染状态切换,9.3 是顶点缓存重排。lab 复现 Profiler 的建树与统计。
剖析实例树:beginProfile 下移 mCurrent
Profiler 维护一个 mRoot 与一个「当前指针」mCurrent。beginProfile 先在 mCurrent->children 里按名字找现有 ProfileInstance:找到了且帧号不同就重置该节点的 calls 与 frameTime;没找到就新建节点并把 parent、hierarchicalLvl 填好。关键的是它把 mCurrent 下移到这个节点,而 currTime 在函数最末尾才记录——尽量贴近被剖析代码的开始:
// OgreMain/src/OgreProfiler.cpp:Profiler::beginProfile(v14.6.3 源码摘录,已删减)
ProfileInstance*& instance = mCurrent->children[profileName];
if(instance)
{ // found existing child.
// Sanity check.
assert(instance->name == profileName);
if(instance->frameNumber != mCurrentFrame)
{ // new frame, reset stats
instance->frame.calls = 0;
instance->frame.frameTime = 0;
instance->frameNumber = mCurrentFrame;
}
}
else
{ // new child!
instance = OGRE_NEW ProfileInstance();
instance->name = profileName;
instance->parent = mCurrent;
instance->hierarchicalLvl = mCurrent->hierarchicalLvl + 1;
}
instance->frameNumber = mCurrentFrame;
mCurrent = instance;
// we do this at the very end of the function to get the most
// accurate timing results
mCurrent->currTime = mTimer->getMicroseconds();
mRoot.hierarchicalLvl 被初始化为 0 - 1(无符号下溢),于是根的孩子层级为 0、孙辈为 1,lab 里用 level("Culling") == 1 验证这一层级链。层级的价值在于渲染 Overlay 时可以按缩进把剖析树画出来。
endProfile:自身计时与父节点 accum 的排除法
endProfile 先做两件防御:栈已经空(mCurrent == &mRoot)时直接返回,避免对空父指针解引用;再校验 mCurrent->name 与传入名是否一致(防「剖析中途被禁用」)。随后取时间差累加到自身 frameTime 与 calls,并且只要父不是根就把这段耗时加进父的 accum:
// OgreMain/src/OgreProfiler.cpp:Profiler::endProfile(v14.6.3 源码摘录,已删减)
if(&mRoot == mCurrent)
return;
// mask groups
if ((groupID & mProfileMask) == 0)
return;
// need a timer to profile!
assert (mTimer && "Timer not set!");
// get the end time of this profile
// we do this as close the beginning of this function as possible
// to get more accurate timing results
const ulong endTime = mTimer->getMicroseconds();
// empty string is reserved for designating an empty parent
assert ((profileName != "") && ("Profile name can't be an empty string"));
// we only process this profile if isn't disabled
// we check the current instance name against the provided profileName as a guard against disabling a profile name /after/ said profile began
if(mCurrent->name != profileName && mDisabledProfiles.find(profileName) != mDisabledProfiles.end())
return;
// calculate the elapsed time of this profile
const ulong timeElapsed = endTime - mCurrent->currTime;
// update parent's accumulator if it isn't the root
if (&mRoot != mCurrent->parent)
{
// add this profile's time to the parent's accumlator
mCurrent->parent->accum += timeElapsed;
}
mCurrent->frame.frameTime += timeElapsed;
++mCurrent->frame.calls;
mLast = mCurrent;
mCurrent = mCurrent->parent;
if (&mRoot == mCurrent)
{
// the stack is empty and all the profiles have been completed
// we have reached the end of the frame so process the frame statistics
// we know that the time elapsed of the main loop is the total time the frame took
mTotalFrameTime = timeElapsed;
注意 accum 的语义:帧内 Frame 开 100us,其中 Culling 30us、Rendering 50us,那么 Frame.accum == 80、Frame.frameTime == 100,自身有效时间 100 - 80 == 20。父的有效时间正是「排除子耗时」的经典口径。lab 用 effective("Frame") == 20u 断言这一点。
帧末统计:processFrameStats 递归算占比
当 mCurrent 回退到根,说明栈已空,帧结束。processFrameStats() 从根的孩子开始递归:每个有调用的节点按 frameTime / mTotalFrameTime 计算 currentTimePercent,并向下传递;没在本帧出现的旧节点被跳过。每次调用还会维护 min/max 时间与总平均(mAverageFrameTime = (mAverageFrameTime + maxFrameTime) * 0.5f),供 Overlay 绘制极值:
// OgreMain/src/OgreProfiler.cpp:Profiler::processFrameStats(v14.6.3 源码摘录,已删减)
void Profiler::processFrameStats(void)
{
Real maxFrameTime = 0;
for (auto& i : mRoot.children)
{
ProfileInstance* child = i.second;
// we set the number of times each profile was called per frame to 0
// because not all profiles are called every frame
child->history.numCallsThisFrame = 0;
if(child->frame.calls > 0)
{
processFrameStats(child, maxFrameTime);
}
}
// Calculate whether the extents are now so out of date they need regenerating
if (mCurrentFrame == 0)
mAverageFrameTime = maxFrameTime;
else
mAverageFrameTime = (mAverageFrameTime + maxFrameTime) * 0.5f;
百分比口径即「自身 frameTime / 总帧时间」——Culling 30us 对 100us 帧正是 30%,Rendering 50us 是 50%。lab 用 0.290.31 与 0.490.51 两个区间验证浮点误差内成立。
性能结论需要相同场景与计量点
Profiler 记录带层级的时间区间。CPU 记录、提交次数和 GPU 时序回答不同问题,尤其不能把 CPU 从 API 返回的时长视作 GPU 完成时间。
先报告固定场景下的对象、三角形和批次,再记录预热、采样窗口和平台。现有 Tiny 探针给出逻辑计数,硬件耗时另采集。
源码定位
OgreMain/src/OgreProfiler.cpp:Profiler::beginProfile(232-260 行)OgreMain/src/OgreProfiler.cpp:Profiler::endProfile(264-372 行)OgreMain/src/OgreProfiler.cpp:Profiler::processFrameStats(374-461 行)OgreMain/include/OgreProfiler.h:ProfileInstance/ProfileFrame(96-194 行)
上游引用固定到 OGRE v14.6.3 源码 。
可运行产物:C++ 最小验证
ProfilerRepro 用一棵 std::map 树复现 begin/end 语义:入点时间在 beginProfile 末尾记录、endProfile 累加自身时间并把子耗时记入父 accum、根层级用无符号下溢得到 -1、mCurrent 回到根时触发帧统计。它与 src/09-1-profiler.cpp 逐字节一致:
// file: src/09-1-profiler.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/09-1-profiler.cpp -o bin/09-1-profiler && ./bin/09-1-profiler
//
// 复现 Profiler 的层次化计时(对应 OgreMain/src/OgreProfiler.cpp 197-372 的
// beginProfile/endProfile 与 374-461 的 processFrameStats):按名字维护一棵
// ProfileInstance 树,mCurrent 随 begin/end 下移与回退;endProfile 把自身
// frameTime 累加给父节点的 accum(排除子耗时);beginProfile 在帧号变化时
// 重置 calls/frameTime;帧末用"自身 frameTime / 总帧时间"算百分比。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"
#include <cstdint>
#include <map>
#include <string>
namespace ogre_repro {
using Micro = uint64_t;
// 对应 OgreProfiler.h 96-108 的 ProfileFrame
struct ProfileFrame {
Micro frameTime = 0;
uint32_t calls = 0;
};
// 对应 OgreProfiler.h 146-194 的 ProfileInstance(瘦身版)
struct ProfileInstance {
std::string name;
ProfileInstance* parent = nullptr;
std::map<std::string, ProfileInstance> children;
ProfileFrame frame;
Micro currTime = 0;
Micro accum = 0;
uint32_t hierarchicalLvl = 0;
uint64_t frameNumber = 0;
double currentTimePercent = 0.0;
};
// 对应 OgreProfiler.cpp 197-372 的 Profiler(beginProfile/endProfile 语义)
class ProfilerRepro {
public:
ProfilerRepro() : mCurrent(&mRoot) {
// 对应 OgreProfiler.cpp 82 行 "mRoot.hierarchicalLvl = 0 - 1"
mRoot.hierarchicalLvl = static_cast<uint32_t>(0 - 1);
}
void setEnabled(bool enabled) { mEnabled = enabled; }
bool getEnabled() const { return mEnabled; }
// 虚拟时钟推进,模拟 OgreTimer::getMicroseconds 的递增
void advance(Micro us) { mClock += us; }
// 对应 Profiler::beginProfile:启用 + 非空名字才入树
void beginProfile(const std::string& profileName) {
if (!mEnabled)
return;
if (profileName.empty())
return;
ProfileInstance& instance = mCurrent->children[profileName];
if (instance.frameNumber != mFrameCounter) {
// new frame, reset stats
instance.frame.calls = 0;
instance.frame.frameTime = 0;
instance.frameNumber = mFrameCounter;
}
instance.name = profileName;
instance.parent = mCurrent;
instance.hierarchicalLvl = mCurrent->hierarchicalLvl + 1;
mCurrent = &instance;
// 对应 "we do this at the very end of the function to get the most
// accurate timing results"
mCurrent->currTime = mClock;
}
// 对应 Profiler::endProfile:时间差计入自身 frameTime,子耗时记入父 accum
void endProfile() {
if (!mEnabled)
return;
// 对应 OgreProfiler.cpp 314-315 行 "if(&mRoot == mCurrent) return;":
// 栈已空(mCurrent 就是 mRoot)时直接返回,避免对 mRoot.parent
// (默认 nullptr)解引用
if (mCurrent == &mRoot)
return;
const Micro timeElapsed = mClock - mCurrent->currTime;
// update parent's accumulator if it isn't the root
if (mCurrent->parent != &mRoot)
mCurrent->parent->accum += timeElapsed;
mCurrent->frame.frameTime += timeElapsed;
++mCurrent->frame.calls;
mCurrent = mCurrent->parent;
if (mCurrent == &mRoot) {
// 栈已空:帧结束,处理帧统计
mTotalFrameTime = timeElapsed;
processFrameStats();
++mFrameCounter;
}
}
// 递归查找(对应 ProfileInstance::watchForMax 的深度优先遍历语义);
// 未入树的 profile(例如被禁用/名字守卫拦截)查询返回 0
const ProfileInstance* findProfile(const std::string& name) const {
return findProfileIn(name, mRoot);
}
Micro frameTime(const std::string& name) const {
const ProfileInstance* p = findProfile(name);
return p ? p->frame.frameTime : 0;
}
uint32_t calls(const std::string& name) const {
const ProfileInstance* p = findProfile(name);
return p ? p->frame.calls : 0;
}
Micro accum(const std::string& name) const {
const ProfileInstance* p = findProfile(name);
return p ? p->accum : 0;
}
Micro effective(const std::string& name) const { return frameTime(name) - accum(name); }
double percent(const std::string& name) const {
const ProfileInstance* p = findProfile(name);
return p ? p->currentTimePercent : 0.0;
}
uint32_t level(const std::string& name) const {
const ProfileInstance* p = findProfile(name);
return p ? p->hierarchicalLvl : 0;
}
// 对应 OgreProfiler.cpp 430-461 的 processFrameStats(void):根的所有孩子
void processFrameStats() {
const double total = static_cast<double>(mTotalFrameTime);
for (auto& [k, inst] : mRoot.children) {
(void)k;
if (inst.frame.calls > 0)
processFrameStats(inst, total);
}
}
private:
const ProfileInstance* findProfileIn(const std::string& name, const ProfileInstance& node) const {
auto it = node.children.find(name);
if (it != node.children.end())
return &it->second;
for (auto& [k, child] : node.children) {
(void)k;
const ProfileInstance* r = findProfileIn(name, child);
if (r)
return r;
}
return nullptr;
}
void processFrameStats(ProfileInstance& inst, double totalFrameTime) {
inst.currentTimePercent =
totalFrameTime > 0.0 ? static_cast<double>(inst.frame.frameTime) / totalFrameTime : 0.0;
for (auto& [k, child] : inst.children) {
(void)k;
if (child.frame.calls > 0)
processFrameStats(child, totalFrameTime);
}
}
ProfileInstance mRoot;
ProfileInstance* mCurrent;
Micro mClock = 0;
Micro mTotalFrameTime = 0;
uint64_t mFrameCounter = 1;
bool mEnabled = false;
};
} // namespace ogre_repro
int main() {
using namespace ogre_repro;
ProfilerRepro prof;
CHECK(!prof.getEnabled()); // 默认禁用,与源码 mEnabled(false) 一致
prof.setEnabled(true);
prof.beginProfile("Frame"); // 主循环:0..100us
prof.advance(20); // 其他工作
prof.beginProfile("Culling");
prof.advance(30);
prof.endProfile();
prof.beginProfile("Rendering");
prof.advance(50);
prof.endProfile();
prof.endProfile(); // Frame = 100us
CHECK_EQ(prof.calls("Culling"), 1u);
CHECK_EQ(prof.calls("Rendering"), 1u);
CHECK_EQ(prof.frameTime("Culling"), 30u);
CHECK_EQ(prof.frameTime("Rendering"), 50u);
CHECK_EQ(prof.frameTime("Frame"), 100u);
// 子耗时进入父 accum,父 effective = 自身 - accum
CHECK_EQ(prof.accum("Frame"), 80u);
CHECK_EQ(prof.effective("Frame"), 20u);
CHECK_EQ(prof.level("Culling"), 1u);
// 帧内百分比 = frameTime / 总帧时间
CHECK(prof.percent("Culling") > 0.29 && prof.percent("Culling") < 0.31);
CHECK(prof.percent("Rendering") > 0.49 && prof.percent("Rendering") < 0.51);
// 第二帧:beginProfile 时帧号变化,calls/frameTime 被重置
prof.beginProfile("Frame");
prof.advance(10);
prof.beginProfile("Culling");
prof.advance(5);
prof.endProfile();
prof.advance(5);
prof.endProfile();
CHECK_EQ(prof.calls("Culling"), 1u);
CHECK_EQ(prof.frameTime("Culling"), 5u);
CHECK_EQ(prof.frameTime("Frame"), 20u);
// 禁用后 begin/end 不再记录
prof.setEnabled(false);
prof.beginProfile("Ghost");
prof.endProfile();
CHECK_EQ(prof.calls("Ghost"), 0u);
// 空名字被守卫拦截
prof.setEnabled(true);
prof.beginProfile("");
prof.endProfile();
CHECK_EQ(prof.frameTime("Frame"), 20u); // 未被空名字污染
return lab::report("9.1 性能剖析器");
}
本机实测(Apple clang 16,clang++ -std=c++20 -Wall):编译通过(零警告),断言 16/16 通过。
小结
- Profiler 是一棵
ProfileInstance树,mCurrent随begin/end下移与回退,同一名字跨帧复用节点。 currTime在beginProfile末尾记录、endTime在endProfile开头获取,尽量贴近被测代码。- 父节点的
accum累加所有子耗时,「父有效时间 = frameTime - accum」正是排除法。 mCurrent回退到根代表帧结束,processFrameStats递归计算每级百分比并维护 min/max 与平均。mRoot.hierarchicalLvl用无符号下溢置为0 - 1,使根的孩子从层级 0 开始。
阅读导航:上一节:8.3 Metal 与 D3D11 后端 · 下一节:9.2 渲染状态切换优化 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。