载入中...
搜索中...
未找到
Profiler.cpp
浏览该文件的文档.
1// eve-hot-path
2#include "profiler/Profiler.h"
3
4#include "common/GpuTimer.h"
5#include "common/Capability.h"
6
7#include <simplesquirrel/simplesquirrel.hpp>
8
9#include <chrono>
10#include <cstdint>
11#include <vector>
12
13namespace eve::profiler {
14
16
17namespace {
18int64_t nowNs() {
19 return std::chrono::duration_cast<std::chrono::nanoseconds>(
20 std::chrono::steady_clock::now().time_since_epoch())
21 .count();
22}
23} // namespace
24
29
33
34void Profiler::setEnabled(bool on) {
35 if (!on || !enabled()) frameBeginNs_ = 0;
37 if (!on) {
38 frameMs_ = 0.f;
39 }
40}
41
43
44const char* Profiler::internScopeName(const std::string& name) {
45 // unordered_set nodes are stable across rehash, so c_str() stays valid for the
46 // module's lifetime; distinct names are bounded by what a game's scripts use.
47 const auto inserted = scopeNames_.insert(name.empty() ? std::string("scope") : name);
48 return inserted.first->c_str();
49}
50
53 frameMs_ = 0.f;
54 captureSequence_ = 0;
55 frameBeginNs_ = 0;
56}
57
58void Profiler::ensureGpuTimer() const {
59 // Retry only while unbound so a late graphics provider can still attach; once
60 // resolved (including to nullptr after a successful provide/revoke cycle is
61 // not re-probed from hot paths — callers rebind by constructing a new module).
62 if (!gpuTimer_) gpuTimer_ = eve::cap::ProviderRef<eve::service::IGpuTimer>::bind();
63}
64
66 frameBeginNs_ = nowNs();
67 ensureGpuTimer();
68}
69
71 if (!enabled() || frameBeginNs_ == 0) return;
72 const double totalMs = static_cast<double>(nowNs() - frameBeginNs_) / 1'000'000.0;
73 frameMs_ = static_cast<float>(totalMs);
75 ++captureSequence_;
76 frameBeginNs_ = 0;
77}
78
79void Profiler::begin(const char* name) {
80 if (!enabled()) return;
81 eve::prof::Profiler::zoneBegin(name ? name : "scope", nullptr);
82}
83
85 if (!enabled()) return;
87}
88
90 if (enabled() && frameBeginNs_ == 0) beginFrame();
91}
92
94
95void Profiler::passBegin(const char* name) {
96 if (!enabled()) return;
97 eve::prof::Profiler::zoneBegin(name ? name : "pass", "graphics");
98}
99
100void Profiler::passEnd(const char* name) {
101 if (!enabled()) return;
103}
104
106
107float Profiler::frameMs() const { return frameMs_; }
108
109float Profiler::gpuFrameMs() const {
110 ensureGpuTimer();
111 return gpuTimer_ ? gpuTimer_->gpuFrameMs() : 0.f;
112}
113
115 if (!hasFrame()) {
117 eve::DiagnosticCode::NotFound, "No completed profiler frame is available",
118 "profiler.frame", {}, "profiler.capture-frame"));
119 }
121 snapshot.sequence = captureSequence_;
122 snapshot.cpuFrameMs = frameMs_;
123 ensureGpuTimer();
124 if (gpuTimer_) {
125 snapshot.gpuTimingAvailable = gpuTimer_->gpuTimingAvailable();
126 if (snapshot.gpuTimingAvailable) snapshot.gpuFrameMs = gpuTimer_->gpuFrameMs();
127 }
128 const auto& samples = eve::prof::Profiler::lastFrame();
129 snapshot.zones.reserve(samples.size());
130 for (const auto& sample : samples) {
131 snapshot.zones.push_back({sample.module, sample.name, sample.thread, sample.selfMs,
132 sample.totalMs, sample.count, sample.minDepth});
133 }
135}
136
137std::string Profiler::textReport() const {
138 std::string report = eve::prof::Profiler::textReport();
139 ensureGpuTimer();
140 if (gpuTimer_ && gpuTimer_->gpuTimingAvailable()) {
141 char buf[64];
142 std::snprintf(buf, sizeof(buf), " GPU graphics-queue span (delayed): %.2f ms\n", gpuTimer_->gpuFrameMs());
143 report += buf;
144 }
145 return report;
146}
147
148namespace {
149ssq::Object zoneRows(HSQUIRRELVM vm, const std::vector<eve::prof::ZoneSample>& samples) {
150 ssq::Array out(vm);
151 for (const auto& s : samples) {
152 ssq::Table t(vm);
153 t.set("module", s.module);
154 t.set("name", s.name);
155 t.set("thread", s.thread);
156 t.set("selfMs", static_cast<float>(s.selfMs));
157 t.set("totalMs", static_cast<float>(s.totalMs));
158 t.set("count", s.count);
159 out.push(t);
160 }
161 return out;
162}
163} // namespace
164
165ssq::Object Profiler::capture() { return zoneRows(vm_, eve::prof::Profiler::lastFrame()); }
166
167ssq::Object Profiler::hotspots(int limit, float minSelfMs) {
168 const std::size_t capped = limit <= 0 ? 0 : static_cast<std::size_t>(limit);
169 return zoneRows(vm_, eve::prof::Profiler::hotspots(capped, static_cast<double>(minSelfMs)));
170}
171
172void Profiler::expose(ssq::Table& table) {
173 if (Profiler* self = Profiler::create()) self->vm_ = table.getHandle();
174 auto cls = table.addClass(name, Profiler::create, false);
175 expose(cls);
176}
177
178void Profiler::expose(ssq::Class& cls) {
179 cls.addFunc("setEnabled", &Profiler::setEnabled);
180 cls.addFunc("enabled", &Profiler::enabled);
181 cls.addFunc("reset", &Profiler::reset);
182 cls.addFunc("beginFrame", &Profiler::beginFrame);
183 cls.addFunc("endFrame", &Profiler::endFrame);
184 // Two shapes have to be bridged here, both discovered by the script smoke test.
185 // `&Profiler::begin` takes `const char*`, which the binding layer treats as an
186 // opaque pointer type and expects an *instance* for, so a script passing a string
187 // failed with "bad cast expected: INSTANCE got: STRING". Converting to std::string
188 // fixes that, but the collector keeps the pointer and reads it at frameMark(), so
189 // the string must also be interned rather than passed as a temporary's c_str().
190 cls.addFunc("begin", [](Profiler* self, const std::string& name) {
191 if (self) self->begin(self->internScopeName(name));
192 });
193 cls.addFunc("end", &Profiler::end);
194 cls.addFunc("hasFrame", &Profiler::hasFrame);
195 cls.addFunc("frameMs", &Profiler::frameMs);
196 cls.addFunc("gpuFrameMs", &Profiler::gpuFrameMs);
197 cls.addFunc("textReport", &Profiler::textReport);
198 cls.addFunc("capture", &Profiler::capture);
199 cls.addFunc("hotspots", &Profiler::hotspots);
200}
201
202} // namespace eve::profiler
const std::string & s
struct SQVM * HSQUIRRELVM
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
std::string name
Definition ECS.cpp:154
Snapshot snapshot
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
float t
ScriptStructure out
int limit
Definition TreeMesh.cpp:166
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static ProviderRef bind()
Resolve I once from the registry.
Definition Capability.h:128
static std::string textReport()
Human-readable report of the last frame.
Definition Profile.cpp:244
static void setEnabled(bool on)
Turns collection on/off globally (off = single-branch no-op).
Definition Profile.cpp:90
static const std::vector< ZoneSample > & lastFrame()
Per-module/per-zone samples of the last frame, sorted by self time.
Definition Profile.cpp:229
static void zoneBegin(const char *name, const char *module=nullptr)
Opens a scoped zone on the current thread.
Definition Profile.cpp:97
static std::vector< ZoneSample > hotspots(std::size_t limit, double minSelfMs)
Copy the hottest zones from the last completed frame.
Definition Profile.cpp:231
static double frameMark()
Finalizes the current frame: snapshots all thread buffers and aggregates them into lastFrame().
Definition Profile.cpp:133
static void reset()
Clears all collected state.
Definition Profile.cpp:123
static void zoneEnd()
Closes the innermost open zone on the current thread.
Definition Profile.cpp:114
static bool hasFrame()
True once at least one frame has been aggregated.
Definition Profile.cpp:227
static bool enabled()
True when collection is active.
Definition Profile.cpp:95
Script-facing wrapper around the engine-wide profiler core (eve::prof, see common/Profile....
Definition Profiler.h:68
void frameBegin() override
Frame begin.
Definition Profiler.cpp:89
void end()
Closes the innermost open user scope.
Definition Profiler.cpp:84
void passEnd(const char *name) override
Pass end.
Definition Profiler.cpp:100
float gpuFrameMs() const
GPU execution time of the last presented frame (0 when unavailable).
Definition Profiler.cpp:109
void begin(const char *name)
Opens a user timing scope under the current frame.
Definition Profiler.cpp:79
void reset()
Clears all collected data.
Definition Profiler.cpp:51
bool hasFrame() const
True once at least one frame has been aggregated.
Definition Profiler.cpp:105
float frameMs() const
Total CPU frame time of the last frame, in milliseconds.
Definition Profiler.cpp:107
const char * internScopeName(const std::string &name)
Intern a script-supplied zone name so it can be handed to the collector.
Definition Profiler.cpp:44
void passBegin(const char *name) override
Pass begin.
Definition Profiler.cpp:95
bool enabled() const
True when collection is active.
Definition Profiler.cpp:42
ssq::Object capture()
Structured report of the last frame.
Definition Profiler.cpp:165
void setEnabled(bool on)
Enables/disables engine-wide collection. Disabled = cheap no-op.
Definition Profiler.cpp:34
ssq::Object hotspots(int limit, float minSelfMs)
Top zones of the last completed frame for quick hotspot triage.
Definition Profiler.cpp:167
~Profiler() override
Profiler.
Definition Profiler.cpp:30
void frameEnd() override
Frame end.
Definition Profiler.cpp:93
eve::Result< ProfilerFrameSnapshot > captureFrame() const
Copy the latest completed frame for editor and diagnostics consumers.
Definition Profiler.cpp:114
std::string textReport() const
Human-readable hotspot report (per module / per zone).
Definition Profiler.cpp:137
void endFrame()
Finalizes the current frame and aggregates the collected zones.
Definition Profiler.cpp:70
void beginFrame()
Marks the start of a frame for total-frame timing.
Definition Profiler.cpp:65
virtual bool gpuTimingAvailable() const =0
True when the renderer captured a valid GPU frame this frame.
virtual float gpuFrameMs() const =0
Graphics-queue interval of the latest completed frame slot, in milliseconds. Delayed by frames in fli...
void setRenderTracer(IRenderTracer *tracer)
Sets the render tracer.
IRenderTracer * renderTracer()
Renders tracer.
EVENGINE_API_FOUNDATION void registerProfilerCapabilities()
Publish the read-only profiler capability (eve::IProfilerQuery).
Owning CPU/GPU profiler snapshot safe to retain across later frames.
Definition Profiler.h:37