Debian Codegraph @

src/base/castletimeutils_frameprofiler.inc

raw
1 {%MainUnit castletimeutils.pas}
2 {
3 Copyright 2019-2024 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 { Part of CastleTimeUtils unit: TCastleFrameProfiler. }
18
19 {$ifdef read_interface}
20
21 type
22 { Various possible per-frame times measured by TCastleFrameProfiler. }
23 TFrameMetric = (
24 { Time in TCastleContainer.EventBeforeRender. }
25 fmBeforeRender,
26
27 { Time of entire rendering, including TCastleContainer.EventRender
28 (so, all TCastleUserInterface.Render and TCastleTransform.Render calls)
29 and including final swap/flush.
30 This includes all other fmRenderXxx times. }
31 fmRender,
32 { Time inside DrawPrimitive2D (but disregarding flushing batching, by TDrawableImage.DrawNoBatch). }
33 fmDrawPrimitive2D,
34 { Time inside TDrawableImage.DrawNoBatch, which TDrawableImage drawing. }
35 fmDrawImage,
36 { Time of swap/flush at the end of rendering, when we flush GPU commands,
37 swap buffers (in case of double buffering), and wait for v-sync.
38 If this is large, it generally means that you have "free" time in the application
39 to use on anything (CPU or GPU work), because you don't use up most of the frame time. }
40 fmRenderSwapFlush,
41 { Time within TCastleScene.Render.
42 Large time means that you have TCastleScene content that is time-consuming to render. }
43 fmRenderScene,
44 { Time within fmRenderScene spent filtering blended shapes.
45 This should not be significant -- otherwise we'll have to optimize this bit in CGE. }
46 fmRenderShapesFilterBlending,
47 { Time within TShapesRenderer.Render spent sorting shapes.
48 If this is significant, then:
49 @unorderedList(
50 @item(On engine side, we have pending ideas how to optimize this sorting,)
51 @item(On user side, consider turning off BlendingSort and OcclusionSort,
52 if you don't need them.)
53 ) }
54 fmRenderCollectedShapesSort,
55 { Time within TShapesRenderer.Render spent doing core of rendering,
56 passing shapes to TRenderer that in turn passes them to OpenGL(ES).
57 This is usually the most significant part of rendering time. }
58 fmRenderCoreRenderer,
59
60 { Time of TCastleContainer.EventUpdate,
61 so most of the things outside of rendering.
62 If this is large, it means you do something time-consuming aside from rendering,
63 like creature AI or physics.
64 This includes all other fmUpdateXxx times. }
65 fmUpdate,
66 fmUpdateGeneratedTextures,
67 fmUpdateScene,
68 fmUpdatePhysics
69 );
70
71 { Profiler gathering statistics about each game frame.
72 Useful to measure where you spend time during the game frame.
73 In contrast to @link(TCastleProfiler), this is not flexible to gather
74 all possible data, or to keep all historic data.
75 It is only specialized to gather some specific data, in each frame,
76 to have statistics from the most recent frames.
77
78 You have to enable the statistics gathering by setting @link(Enabled) to @true.
79 That's it.
80 In the log (see https://castle-engine.io/manual_log.php )
81 you will see a frame statistics, displayed after every 60 frames gathered.
82
83 Optionally, you can also report additional
84 measurements during the frame.
85 Do this by calling @link(Start) and @link(Stop) with String parameter,
86 like this:
87
88 @longCode(#
89 procedure TMyGameState.Update;
90 begin
91 FrameProfiler.Start('MyTimeConsumingOperation');
92 MyTimeConsumingOperation;
93 FrameProfiler.Stop('MyTimeConsumingOperation');
94 end;
95 #)
96
97 Use this class only through the singleton instance @link(FrameProfiler).
98
99 The easiest way to enable this and view the data is through
100 Castle Game Engine inspector. Just press F8 in a debug build to view it.
101 }
102 TCastleFrameProfiler = class
103 private
104 const
105 MaxRecordFrames = 1000;
106 MaxUserMetrics = 16;
107 MetricsPerFrame =
108 // frame total time
109 1
110 // time, for each TFrameMetric
111 + Ord(High(TFrameMetric)) + 1
112 // user metrics, MaxUserMetrics for render, update, other
113 + 3 * MaxUserMetrics;
114 IndexTotalMetric = 0;
115 type
116 TMetricIndex = 0..MetricsPerFrame - 1;
117 TUserMetric = 0..MaxUserMetrics - 1;
118 var
119 FEnabled: Boolean;
120 FramesTimes: array [0..MaxRecordFrames - 1, TMetricIndex] of TFloatTime;
121 CurrentFrameStarted: array [TMetricIndex] of Boolean;
122 { Using ProcessTimer would be better for calculations,
123 but on Unix (the only platform where it's different from Timer) it has
124 too low precision (1/100 of second) to be useful for this. }
125 CurrentFrameStart: array [TMetricIndex] of TTimerResult;
126 CurrentFrame: Integer;
127 // if InitialFrame > CurrentFrame, then it means statistics wraps in FramesTimes array
128 InitialFrame: Integer;
129 UserMetricsRenderNames: array [TUserMetric] of String;
130 UserMetricsUpdateNames: array [TUserMetric] of String;
131 UserMetricsOtherNames: array [TUserMetric] of String;
132 FFramesForSummary: Cardinal;
133 FOnSummaryAvailable: TNotifyEvent;
134 FLogSummary: Boolean;
135 function IndexFrameMetric(const Metric: TFrameMetric): TMetricIndex;
136 function IndexUserMetric(const Name: String; out Metric: TMetricIndex): Boolean;
137 { StartCore and StopCore unify all metrics (frame total, TFrameMetric, user metrics)
138 as a simple integer index. }
139 procedure StartCore(const Metric: TMetricIndex);
140 procedure StopCore(const Metric: TMetricIndex);
141 { Gather frame information from start.
142 This is useful if you're going to keep @link(Enabled) = @false for a longer amount of time,
143 and then turn @link(Enabled) back to @true.
144 You don't want to sum new frames to the old frames and make statistics from it. }
145 procedure Reset;
146 procedure SetEnabled(const Value: Boolean);
147 public
148 const
149 DefaultFramesForSummary = 60;
150
151 constructor Create;
152 { No data is gathered when Enabled = false, the calls to @link(StartFrame),
153 @link(Start), @link(Stop) are ignored then. }
154 property Enabled: Boolean read FEnabled write SetEnabled;
155 procedure StartFrame;
156 procedure Start(const Metric: TFrameMetric); overload;
157 procedure Stop(const Metric: TFrameMetric); overload;
158 procedure Start(const UserMetric: String); overload;
159 procedure Stop(const UserMetric: String); overload;
160
161 { Gather this many frames for a summary. }
162 property FramesForSummary: Cardinal read FFramesForSummary write FFramesForSummary
163 default DefaultFramesForSummary;
164
165 { Summary of times, use only from @link(OnSummaryAvailable).
166 SummaryTotalFrameTime is the total time we spent this frame.
167 SummaryTime are times of particular things within this frame.
168 @groupBegin }
169 function SummaryTotalFrameTime: TFloatTime;
170 function SummaryTime(const FrameMetric: TFrameMetric): TFloatTime; overload;
171 function SummaryTime(const UserMetric: String): TFloatTime; overload;
172 { @groupEnd }
173
174 { Notification when the summary is available, i.e. we have gathered FramesForSummary frames. }
175 property OnSummaryAvailable: TNotifyEvent read FOnSummaryAvailable write FOnSummaryAvailable;
176
177 { When the summary is available, output details to log. }
178 property LogSummary: Boolean read FLogSummary write FLogSummary default false;
179 end;
180
181 { Single instance of @link(TCastleFrameProfiler) that you can use for frame profiling.
182 See @link(TCastleFrameProfiler) for more documentation and examples.
183 Castle Game Engine uses this to report render/update times automatically. }
184 function FrameProfiler: TCastleFrameProfiler;
185
186 {$endif read_interface}
187
188 {$ifdef read_implementation}
189
190 { internal globals ----------------------------------------------------------- }
191
192 // not used for now
193 // function FrameMetricToStr(const Metric: TFrameMetric): String;
194 // begin
195 // WriteStr(Result, Metric);
196 // end;
197
198 { TCastleFrameProfiler ------------------------------------------------------- }
199
200 constructor TCastleFrameProfiler.Create;
201 begin
202 inherited;
203 { Since the memory usage may grow quickly once increasing MaxUserMetrics, watch it }
204 // WritelnLog('FrameProfiler created, eats around %f MB of memory', [
205 // (SizeOf(FramesTimes) +
206 // SizeOf(CurrentFrameStarted) +
207 // SizeOf(CurrentFrameStart)) / (1024 * 1024)
208 // ]);
209 FFramesForSummary := DefaultFramesForSummary;
210 end;
211
212 procedure TCastleFrameProfiler.StartCore(const Metric: TMetricIndex);
213 begin
214 if not FEnabled then Exit;
215
216 if (Metric <> IndexFrameMetric(fmUpdateGeneratedTextures)) and
217 CurrentFrameStarted[IndexFrameMetric(fmUpdateGeneratedTextures)] then
218 Exit; // do not measure rendering times inside fmUpdateGeneratedTextures, they make output confusing
219
220 if CurrentFrameStarted[Metric] then
221 begin
222 WritelnWarning('Frame metric %d not stopped yet (but started again). Possible causes: mismatched Start/Stop calls, or broken by exception', [
223 Metric
224 ]);
225 end else
226 begin
227 CurrentFrameStarted[Metric] := true;
228 CurrentFrameStart[Metric] := Timer;
229 end;
230 end;
231
232 procedure TCastleFrameProfiler.StopCore(const Metric: TMetricIndex);
233 begin
234 if not FEnabled then Exit;
235
236 if (Metric <> IndexFrameMetric(fmUpdateGeneratedTextures)) and
237 CurrentFrameStarted[IndexFrameMetric(fmUpdateGeneratedTextures)] then
238 Exit; // do not measure rendering times inside fmUpdateGeneratedTextures, they make output confusing
239
240 if not CurrentFrameStarted[Metric] then
241 begin
242 WritelnWarning('Frame metric %d not started. Possible cause: called FrameProfiler.Enabled between Start/Stop, this can be ignored.', [
243 Metric
244 ]);
245 end else
246 begin
247 FramesTimes[CurrentFrame, Metric] := FramesTimes[CurrentFrame, Metric] +
248 CurrentFrameStart[Metric].ElapsedTime;
249 CurrentFrameStarted[Metric] := false;
250 end;
251 end;
252
253 function TCastleFrameProfiler.SummaryTotalFrameTime: TFloatTime;
254 begin
255 Result := FramesTimes[CurrentFrame, IndexTotalMetric];
256 end;
257
258 function TCastleFrameProfiler.SummaryTime(const FrameMetric: TFrameMetric): TFloatTime;
259 begin
260 Result := FramesTimes[CurrentFrame, IndexFrameMetric(FrameMetric)];
261 end;
262
263 function TCastleFrameProfiler.SummaryTime(const UserMetric: String): TFloatTime;
264 var
265 Metric: TMetricIndex;
266 begin
267 if not IndexUserMetric(UserMetric, Metric) then
268 raise Exception.CreateFmt('Cannot find user metric "%s"', [UserMetric]);
269 Result := FramesTimes[CurrentFrame, Metric];
270 end;
271
272 procedure TCastleFrameProfiler.StartFrame;
273
274 procedure DoLogSummary;
275 var
276 TotalTime: TFloatTime;
277
278 function PercentTime(const MetricIndex: TMetricIndex): Integer; overload;
279 begin
280 Result := Round(100 * FramesTimes[CurrentFrame, MetricIndex] / TotalTime);
281 end;
282
283 function PercentTime(const FrameMetric: TFrameMetric): Integer; overload;
284 begin
285 Result := PercentTime(IndexFrameMetric(FrameMetric));
286 end;
287
288 function DisplayUserMetrics(const Names: array of String; const InitialIndex: TMetricIndex): String;
289 var
290 I: TUserMetric;
291 begin
292 Result := '';
293 for I := 0 to MaxUserMetrics - 1 do
294 if Names[I] <> '' then
295 Result := Result + Format(' - %s: %d%%' + NL, [
296 Names[I],
297 PercentTime(InitialIndex + I)
298 ]);
299 end;
300
301 begin
302 TotalTime := SummaryTotalFrameTime;
303 WritelnLogMultiline('FrameProfiler', Format(
304 'Frame time: %f secs (we should have %f FPS based on this):' + NL +
305 '- BeforeRender: %d%%' + NL +
306 '- Render: %d%% (%f secs, we should have %f "only render FPS" based on this)' + NL +
307 ' - DrawPrimitive2D: %d%%' + NL +
308 ' - TDrawableImage.DrawNoBatch: %d%%' + NL +
309 ' - TCastleScene.Render: %d%%' + NL +
310 ' - ShapesFilterBlending: %d%%' + NL +
311 ' - Sorting shapes in TShapesRenderer.Render: %d%%' + NL +
312 ' - TRenderer: %d%%' + NL +
313 ' - Swap / flush buffers (includes waiting for v-sync): %d%%' + NL +
314 '%s' +
315 '- Update: %d%%' + NL +
316 ' - TCastleScene.UpdateGeneratedTextures: %d%%' + NL +
317 ' - TCastleSceneCore.Update: %d%%' + NL +
318 ' - Update Kraft Physics: %d%% (%.5f secs)' + NL +
319 '%s' +
320 '- Other:' + NL +
321 '%s'
322 , [
323 TotalTime,
324 1 / TotalTime,
325 PercentTime(fmBeforeRender),
326 PercentTime(fmRender),
327 FramesTimes[CurrentFrame, IndexFrameMetric(fmRender)],
328 1 / FramesTimes[CurrentFrame, IndexFrameMetric(fmRender)],
329 PercentTime(fmDrawPrimitive2D),
330 PercentTime(fmDrawImage),
331 PercentTime(fmRenderScene),
332 PercentTime(fmRenderShapesFilterBlending),
333 PercentTime(fmRenderCollectedShapesSort),
334 PercentTime(fmRenderCoreRenderer),
335 PercentTime(fmRenderSwapFlush),
336 DisplayUserMetrics(UserMetricsRenderNames, 1 + Ord(High(TFrameMetric)) + 1 + 0),
337 PercentTime(fmUpdate),
338 PercentTime(fmUpdateGeneratedTextures),
339 PercentTime(fmUpdateScene),
340 PercentTime(fmUpdatePhysics),
341 FramesTimes[CurrentFrame, IndexFrameMetric(fmUpdatePhysics)],
342 DisplayUserMetrics(UserMetricsUpdateNames, 1 + Ord(High(TFrameMetric)) + 1 + MaxUserMetrics),
343 DisplayUserMetrics(UserMetricsOtherNames , 1 + Ord(High(TFrameMetric)) + 1 + 2 * MaxUserMetrics)
344 ]));
345 end;
346
347 var
348 OtherMetric: TMetricIndex;
349 begin
350 if not FEnabled then Exit;
351
352 { Finish previous frame, if started.
353 For IndexTotalMetric, we do not except the user code to ever call
354 StopCore(IndexTotalMetric). }
355 if CurrentFrameStarted[IndexTotalMetric] then
356 begin
357 Assert(FramesTimes[CurrentFrame, IndexTotalMetric] = 0); // should be cleared at the beginning of frame
358 FramesTimes[CurrentFrame, IndexTotalMetric] := CurrentFrameStart[IndexTotalMetric].ElapsedTime;
359
360 // check do have any other time started in this frame, and not stopped
361 for OtherMetric := Low(TMetricIndex) to High(TMetricIndex) do
362 if (OtherMetric <> IndexTotalMetric) and
363 CurrentFrameStarted[OtherMetric] then
364 begin
365 WritelnWarning('Frame metric %d not stopped within this frame. Possible causes: mismatched Start/Stop calls, or broken by exception', [
366 OtherMetric
367 ]);
368 FramesTimes[CurrentFrame, OtherMetric] := FramesTimes[CurrentFrame, OtherMetric] +
369 CurrentFrameStart[OtherMetric].ElapsedTime;
370 end;
371
372 if (CurrentFrame > 0) and (CurrentFrame mod FramesForSummary = 0) then
373 begin
374 if Assigned(OnSummaryAvailable) then
375 OnSummaryAvailable(Self);
376 if LogSummary then
377 DoLogSummary;
378 end;
379
380 CurrentFrame := (CurrentFrame + 1) mod MaxRecordFrames;
381 FillChar(FramesTimes[CurrentFrame], SizeOf(FramesTimes[CurrentFrame]), 0);
382 FillChar(CurrentFrameStarted, SizeOf(CurrentFrameStarted), 0);
383 if InitialFrame = CurrentFrame then
384 InitialFrame := (InitialFrame + 1) mod MaxRecordFrames;
385 end;
386
387 StartCore(IndexTotalMetric);
388 end;
389
390 procedure TCastleFrameProfiler.Reset;
391 begin
392 CurrentFrame := 0;
393 InitialFrame := 0;
394 FillChar(FramesTimes[CurrentFrame], SizeOf(FramesTimes[CurrentFrame]), 0);
395 FillChar(CurrentFrameStarted, SizeOf(CurrentFrameStarted), 0);
396 end;
397
398 procedure TCastleFrameProfiler.SetEnabled(const Value: Boolean);
399 begin
400 if FEnabled <> Value then
401 begin
402 FEnabled := Value;
403 if not Value then // for now, we just always Reset when setting Enabled to false
404 Reset;
405 end;
406 end;
407
408 function TCastleFrameProfiler.IndexFrameMetric(const Metric: TFrameMetric): TMetricIndex;
409 begin
410 Result := 1 + Ord(Metric);
411 end;
412
413 function TCastleFrameProfiler.IndexUserMetric(const Name: String; out Metric: TMetricIndex): Boolean;
414
415 function FindUserMetricName(var Names: array of String; out Index: TUserMetric): Boolean;
416 var
417 Idx: TUserMetric;
418 begin
419 for Idx := Low(TUserMetric) to High(TUserMetric) do
420 if Names[Idx] = Name then
421 begin
422 Index := Idx;
423 Exit(true);
424 end;
425
426 // otherwise look for an empty slot
427 for Idx := Low(TUserMetric) to High(TUserMetric) do
428 if Names[Idx] = '' then
429 begin
430 Names[Idx] := Name;
431 Index := Idx;
432 Exit(true);
433 end;
434
435 WritelnWarning('Cannot find slot to store user metrics %s. Increase MaxUserMetrics in CastleTimeUtils.', [
436 Name
437 ]);
438 Result := false;
439 end;
440
441 var
442 Multiplier: Integer;
443 Index: TUserMetric;
444 begin
445 Assert(Name <> '', 'User metric name cannot be empty, as we internally use empty metric names to mean "uninitialized"');
446
447 { We have MaxUserMetrics slots for custom metrics during rendering,
448 another MaxUserMetrics slots for custom metrics during updating,
449 another MaxUserMetrics slots for custom metrics during neither of rendering/updating. }
450 if CurrentFrameStarted[IndexFrameMetric(fmRender)] then
451 begin
452 if not FindUserMetricName(UserMetricsRenderNames, Index) then Exit(false);
453 Multiplier := 0;
454 end else
455 if CurrentFrameStarted[IndexFrameMetric(fmUpdate)] then
456 begin
457 if not FindUserMetricName(UserMetricsUpdateNames, Index) then Exit(false);
458 Multiplier := 1;
459 end else
460 begin
461 if not FindUserMetricName(UserMetricsOtherNames, Index) then Exit(false);
462 Multiplier := 2;
463 end;
464
465 Result := true;
466 Metric := 1 +
467 Ord(High(TFrameMetric)) + 1 +
468 (Multiplier * MaxUserMetrics) + Index;
469 end;
470
471 procedure TCastleFrameProfiler.Start(const Metric: TFrameMetric);
472 begin
473 StartCore(IndexFrameMetric(Metric));
474 end;
475
476 procedure TCastleFrameProfiler.Stop(const Metric: TFrameMetric);
477 begin
478 StopCore(IndexFrameMetric(Metric));
479 end;
480
481 procedure TCastleFrameProfiler.Start(const UserMetric: String);
482 var
483 Metric: TMetricIndex;
484 begin
485 if not FEnabled then Exit;
486 if not IndexUserMetric(UserMetric, Metric) then Exit;
487 StartCore(Metric);
488 end;
489
490 procedure TCastleFrameProfiler.Stop(const UserMetric: String);
491 var
492 Metric: TMetricIndex;
493 begin
494 if not FEnabled then Exit;
495 if not IndexUserMetric(UserMetric, Metric) then Exit;
496 StopCore(Metric);
497 end;
498
499 { global --------------------------------------------------------------------- }
500
501 var
502 FFrameProfiler: TCastleFrameProfiler;
503
504 function FrameProfiler: TCastleFrameProfiler;
505 begin
506 if FFrameProfiler = nil then
507 FFrameProfiler := TCastleFrameProfiler.Create;
508 Result := FFrameProfiler;
509 end;
510
511 {$endif read_implementation}