Debian Codegraph @

src/base/castletimeutils_profiler.inc

raw
1 {%MainUnit castletimeutils.pas}
2 {
3 Copyright 2018-2022 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: TCastleProfiler. }
18
19 {$ifdef read_interface}
20
21 type
22 { Structure obtained by calling @link(TCastleProfiler.Start). }
23 TCastleProfilerTime = record
24 private
25 FTimeStart: TTimerResult;
26 FProcessTimeStart: TProcessTimerResult;
27 FTime: TObject; //< Always TCastleProfiler.TTime
28
29 { Summary of the speed measurements gathered for this TCastleProfilerTime.
30 Useful to investigate time under this TCastleProfilerTime,
31 as opposed to @link(TCastleProfiler.Summary Profiler.Summary) that
32 displays complete profile of everything that happened.
33
34 Note: using Summary on a stopped TCastleProfilerTime is not allowed,
35 may fail with Access Violation.
36 For this reason, this method was removed, as it was a trap.
37 Using LogSummary for Stop instead is both easier, and safe. }
38 //function Summary(const Indent: String = ''): string;
39 public
40 { Elapsed time in seconds since calling @link(TCastleProfiler.Start)
41 that returned this. Useful if you use @link(TCastleProfiler),
42 but in addition to @link(TCastleProfiler.Summary) you also want to show
43 the operation time in some other way. }
44 function ElapsedTime: TFloatTime;
45 end;
46
47 { Profiler, to measure the speed of execution of your code.
48 This is usually used only through the singleton @link(Profiler).
49
50 The profiler is automatically used by various Castle Game Engine loading
51 routines. It presents the easiest way to answer questions like
52 "which game asset is the most expensive to load".
53
54 To get the profile:
55
56 @orderedList(
57 @item(
58 Set @link(Enabled) to @true as early as possible,
59 like in the "initialization" section of your main game unit.)
60
61 @item(
62 The engine will automatically send to log a profile after
63 @link(TCastleApplication.OnInitialize) finished,
64 which is a usual place when loading takes place in simple CGE applications.
65
66 You don't need to do anything, just make sure you have logging enabled
67 (call @link(InitializeLog)).)
68
69 @item(
70 You can display the profile @link(Summary) at any point in your application,
71 in any way you like.
72 For example by
73
74 @longCode(#
75 WritelnLogMultiline('Time Profile', Profiler.Summary);
76 #)
77
78 An alternative way to display the profile is to pass @true as a 2nd
79 argument to any @link(Stop) call. This allows to display a profile
80 limited to given @link(Start) .. @link(Stop) pair.
81 )
82 )
83
84 To send your own time information to the profile,
85 call @link(Start) and @link(Stop) methods around a given time-consuming task.
86 We will measure time and automatically build a tree of tasks
87 (when one larger task contains several smaller tasks).
88
89 Contrary to profilers like Valgrind or Gprof
90 (see
91 https://castle-engine.io/manual_optimization.php#section_profiling ,
92 https://castle-engine.io/profiling_using_valgrind ),
93 this profiler does not automatically gather everything.
94 On the other hand, this profiler works on all platforms supported by CGE,
95 and is trivial to use.
96 }
97 TCastleProfiler = class
98 private
99 {$ifndef PASDOC}
100 // TODO: for PasDoc: Something here confuses PasDoc, although it generally can handle nested classes.
101
102 type
103 // TTimes = class; // such forward declaration confuses C++ Builder
104
105 TTime = class
106 Description: String;
107 Time, ProcessTime: TFloatTime;
108 Finished: Boolean;
109 Children: TObject; // nil if empty; always TTimes, but declaring it as such confuses C++ Builder
110 destructor Destroy; override;
111 function Summary(const Indent: String): String;
112 end;
113
114 TTimeList = {$ifdef FPC}specialize{$endif} TObjectList<TTime>;
115
116 TTimes = class(TTimeList)
117 procedure Sort;
118 function Summary(const Indent: String): String;
119 end;
120
121 var
122 FEnabled: boolean;
123
124 { Collected times tree. }
125 Times: TTimes;
126
127 { The currently started (but not stopped) TTime structures. }
128 CurrentStack: TTimeList;
129
130 {$endif}
131 public
132 constructor Create;
133 destructor Destroy; override;
134
135 { Whether to gather speed measurements.
136 When not enabled, the @link(Start) and @link(Stop) methods do as little
137 as possible to not waste time. }
138 property Enabled: boolean read FEnabled write FEnabled;
139
140 { Summary of the gathered speed measurements. }
141 function Summary: string;
142
143 { Clear currently gathered times.
144
145 Do not call this when some time measure is started but not yet stopped
146 Currently, this will cause such time measure to be rejected,
147 and stopping it will cause a one-time warning,
148 but don't depend on this exact behavior in the future.
149 We will always gracefully accept this case (not crash). }
150 procedure Clear; deprecated 'This method is not reliable (may cause crashes when used between Start/Stop) and also not comfortable. To display partial profile information, better use Stop with 2nd argument true.';
151
152 { Start a task which execution time will be measured.
153 You @italic(must) later call @link(Stop) with
154 the returned TCastleProfilerTime value.
155
156 Typical usage looks like this:
157
158 @longCode(#
159 procedure TMyClass.LoadSomething;
160 var
161 TimeStart: TCastleProfilerTime;
162 begin
163 TimeStart := Profiler.Start('Loading something (TMyClass)');
164 try
165 // do the time-consuming loading now...
166 finally
167 Profiler.Stop(TimeStart);
168 end;
169 end;
170 #)
171
172 If you don't use the "finally" clause to @italic(always) call
173 the matching @link(Stop), and an exception may occur in LoadSomething,
174 then you will have an unmatched Start / Stop calls.
175 The profiler output is undefined in this case.
176 (However, we guarantee that the profiler will not crash or otherwise cause
177 problems in the application.)
178 So, you do not really have to wrap this in "try ... finally ... end" clause,
179 if it's acceptable that the profiler output is useless
180 in exceptional situations.
181
182 @seealso Stop
183 }
184 function Start(const Description: String): TCastleProfilerTime;
185
186 { Stop a task. This call must match earlier @link(Start) call.
187
188 If LogSummary, and profiling is @link(Enabled), we will output (to CastleLog)
189 a summary of things that happened within this particular TCastleProfilerTime
190 instance (between it's start and stop).
191 This is useful when you are interested not only in adding this
192 TCastleProfilerTime to the profiler tree, but also in immediately viewing the
193 times in this TCastleProfilerTime subtree.
194
195 If LogSummary and LogSummaryOnlyIfNonTrivial, then the summary will be output
196 only if it's larger than some ignorable amount of time (right now: 1 milisecond).
197 This is useful to output only things that take non-trivial amount of time.
198
199 @seealso Start }
200 procedure Stop(const TimeStart: TCastleProfilerTime;
201 const LogSummary: Boolean = false;
202 const LogSummaryOnlyIfNonTrivial: Boolean = false);
203 end;
204
205 { Single instance of TCastleProfiler that you can use for all profiling.
206 Castle Game Engine uses it to report loading times of various assets
207 automatically. }
208 function Profiler: TCastleProfiler;
209
210 {$endif read_interface}
211
212 {$ifdef read_implementation}
213
214 const
215 SProfileSummary =
216 'Profile (speed of execution).' + NL +
217 'Each line shows time, followed by [time spent in this process], followed by description.' + NL +
218 'Lines are sorted within each group, to show the most expensive operation at the top.' + NL +
219 NL;
220
221 { TCastleProfilerTime -------------------------------------------------------- }
222
223 function TCastleProfilerTime.ElapsedTime: TFloatTime;
224 begin
225 Result := FTimeStart.ElapsedTime;
226 end;
227
228 {
229 function TCastleProfilerTime.Summary(const Indent: String): string;
230 var
231 T: TCastleProfiler.TTime;
232 begin
233 T := TCastleProfiler.TTime(FTime);
234 Result := SProfileSummary + T.Summary(Indent);
235 end;
236 }
237
238 { TCastleProfiler.TTime ------------------------------------------------------ }
239
240 function TCastleProfiler.TTime.Summary(const Indent: String): String;
241 begin
242 if not Finished then
243 Result := Indent + Format('UNFINISHED - %s', [Description]) + NL
244 else
245 Result := Indent + Format('%f [%f] - %s', [Time, ProcessTime, Description]) + NL;
246 if Children <> nil then
247 Result := Result + TTimes(Children).Summary(Indent + '> ');
248 end;
249
250 destructor TCastleProfiler.TTime.Destroy;
251 begin
252 FreeAndNil(Children);
253 inherited;
254 end;
255
256 { TCastleProfiler.TTimes ----------------------------------------------------- }
257
258 { Helper for TTimes.Sort }
259 function TimeSort({$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} Value1, Value2: TCastleProfiler.TTime): Integer;
260 begin
261 Result := Sign(Value2.Time - Value1.Time);
262 end;
263
264 procedure TCastleProfiler.TTimes.Sort;
265 type
266 TTimeComparer = {$ifdef FPC}specialize{$endif} TComparer<TTime>;
267 begin
268 inherited Sort(TTimeComparer.Construct({$ifdef FPC}@{$endif} TimeSort));
269 end;
270
271 function TCastleProfiler.TTimes.Summary(const Indent: String): String;
272 var
273 I: Integer;
274 begin
275 Sort;
276 Result := '';
277 for I := 0 to Count - 1 do
278 Result := Result + Items[I].Summary(Indent);
279 end;
280
281 { TCastleProfiler ------------------------------------------------------------------ }
282
283 var
284 FProfiler: TCastleProfiler;
285
286 function Profiler: TCastleProfiler;
287 begin
288 if FProfiler = nil then
289 FProfiler := TCastleProfiler.Create;
290 Result := FProfiler;
291 end;
292
293 constructor TCastleProfiler.Create;
294 begin
295 inherited;
296 Times := TTimes.Create(true);
297 CurrentStack := TTimeList.Create(false);
298 end;
299
300 destructor TCastleProfiler.Destroy;
301 begin
302 FreeAndNil(CurrentStack);
303 FreeAndNil(Times);
304 inherited;
305 end;
306
307 function TCastleProfiler.Summary: string;
308 begin
309 Result := SProfileSummary + Times.Summary('');
310 end;
311
312 function TCastleProfiler.Start(const Description: String): TCastleProfilerTime;
313 var
314 ParentTimes: TTimes;
315 T, Last: TTime;
316 begin
317 if not Enabled then
318 begin
319 Result.FTime := nil;
320 Exit; // rest of Result doesn't matter
321 end;
322
323 T := TTime.Create;
324 T.Description := Description;
325
326 if CurrentStack.Count <> 0 then
327 begin
328 Last := CurrentStack.Last;
329 if Last.Children = nil then
330 Last.Children := TTimes.Create(true);
331 ParentTimes := TTimes(Last.Children);
332 end else
333 ParentTimes := Times;
334
335 ParentTimes.Add(T);
336 CurrentStack.Add(T);
337
338 Result.FTime := T;
339 Result.FTimeStart := Timer;
340 Result.FProcessTimeStart := ProcessTimer;
341 end;
342
343 procedure TCastleProfiler.Stop(const TimeStart: TCastleProfilerTime;
344 const LogSummary, LogSummaryOnlyIfNonTrivial: Boolean);
345 var
346 T: TTime;
347 IndexInStack: Integer;
348 begin
349 if TimeStart.FTime = nil then
350 Exit; // Start was called when Enabled = false
351
352 T := TTime(TimeStart.FTime);
353
354 if T.Finished then
355 WritelnWarning('Called Stop on the same TCastleProfilerTime instance (%s) multiple times',
356 [T.Description]);
357
358 T.Finished := true;
359 T.Time := TimeStart.FTimeStart.ElapsedTime;
360 T.ProcessTime := TimeStart.FProcessTimeStart.ElapsedTime;
361
362 // Call this before CurrentStack.Delete, which may free the T instance
363 if LogSummary and
364 ( (not LogSummaryOnlyIfNonTrivial) or (T.Time > 0.01) ) then
365 WritelnLogMultiline(T.Description, T.Summary(''));
366
367 if (CurrentStack.Count <> 0) and
368 (CurrentStack.Last = T) then
369 CurrentStack.Delete(CurrentStack.Count - 1)
370 else
371 begin
372 WritelnWarning('Mismatched Profiler.Start/Stop calls, the currently stopped time measurement (%s) is not the last measurement started (%s). Use try...finally to always run "Profiler.Stop" for each "Profiler.Start".', [
373 T.Description,
374 CurrentStack.Last.Description
375 ]);
376 IndexInStack := CurrentStack.IndexOf(T);
377 if IndexInStack <> - 1 then
378 CurrentStack.DeleteRange(IndexInStack, CurrentStack.Count - IndexInStack)
379 else
380 WritelnWarning('Cannot find in stack the start of "%s", profiler information is corrupt, possible Access Violations errors later', [
381 T.Description
382 ]);
383 end;
384 end;
385
386 procedure TCastleProfiler.Clear;
387 begin
388 Times.Clear;
389 CurrentStack.Clear;
390 end;
391
392 {$endif read_implementation}