Debian Codegraph @

src/base/castletimeutils_timer.inc

raw
1 {%MainUnit castletimeutils.pas}
2 {
3 Copyright 2000-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: Timer, measuring real time. }
18
19 {$ifdef read_interface}
20
21 type
22 { Current time from @link(Timer). }
23 TTimerResult = record
24 private
25 { The type of this could be platform-dependent. But for now, all platforms
26 are happy with QWord. }
27 Value: QWord;
28 public
29 { Seconds passed since this time sample up to now.
30 Equivalent to @code(TimerSeconds(Timer, Self)) }
31 function ElapsedTime: TFloatTime;
32
33 { Holds non-zero value. Use to detect whether this TTimerResult comes from Timer
34 call, or is just a zero field in new class instance. }
35 function Initialized: Boolean;
36
37 { Expose internal Value for Kraft when USE_CASTLE_TIME_UTILS. }
38 {$ifndef PASDOC}
39 {$if (not defined(FPC)) and (not defined(MSWINDOWS))}
40 property InternalValue: QWord read Value;
41 {$endif}
42 {$endif}
43 end;
44
45 { Timer to measure (real) time passed during some operations.
46 It is a "real" time, which means that subtracting two values measures
47 the actual time that passed between two events.
48 Contrast this with @link(ProcessTimer) that tries to measure
49 only CPU time used by the current process.
50
51 Call Timer twice, and calculate the difference (in seconds)
52 using the TimerSeconds. Like this:
53
54 @longCode(#
55 var
56 TimeStart: TTimerResult;
57 Seconds: TFloatTime;
58 begin
59 TimeStart := Timer;
60 // ... do something time-consuming ...
61 Seconds := TimerSeconds(Timer, TimeStart);
62 // or: Seconds := TimeStart.ElapsedTime;
63 WritelnLog('Seconds passed: %f', [Seconds]);
64 end;
65 #)
66 }
67 function Timer: TTimerResult;
68
69 { Subtract two times obtained from @link(Timer),
70 A-B, return a difference in seconds. }
71 function TimerSeconds(const A, B: TTimerResult): TFloatTime;
72
73 {$endif read_interface}
74
75 {$ifdef read_implementation}
76
77 { timer ---------------------------------------------------------- }
78
79 {$if defined(MSWINDOWS)}
80
81 type
82 TTimerFrequency = QWord;
83 TTimerState = (tsNotInitialized, tsQueryPerformance, tsCastleGetTickCount64);
84
85 var
86 FTimerState: TTimerState = tsNotInitialized;
87 FTimerFrequency: TTimerFrequency;
88
89 { Set FTimerState to something <> tsNotInitialized.
90 Also set FTimerFrequency. }
91 procedure InitTimer;
92 begin
93 if QueryPerformanceFrequency(Int64(FTimerFrequency)) then
94 FTimerState := tsQueryPerformance else
95 begin
96 FTimerState := tsCastleGetTickCount64;
97 FTimerFrequency := 1000;
98 end;
99 end;
100
101 function TimerFrequency: TTimerFrequency;
102 begin
103 if FTimerState = tsNotInitialized then InitTimer;
104
105 Result := FTimerFrequency;
106 end;
107
108 function Timer: TTimerResult;
109 begin
110 if FTimerState = tsNotInitialized then InitTimer;
111
112 if FTimerState = tsQueryPerformance then
113 QueryPerformanceCounter(Int64(Result.Value))
114 else
115 begin
116 Result.Value := CastleGetTickCount64;
117 end;
118 end;
119
120
121 {$elseif defined(CASTLE_NINTENDO_SWITCH)}
122 const
123 TimerFrequency = 1000;
124
125 function Timer: TTimerResult;
126 begin
127 Result.Value := CastleGetTickCount64;
128 end;
129
130 {$elseif defined(ANDROID) or defined(FREEBSD) or defined(LINUX)}
131
132 { Use clock_gettime(CLOCK_MONOTONIC,...).
133
134 Android: has three clocks, we need to use clock which never leaps forward
135 or backward. This clock we can get by clock_gettime(CLOCK_MONOTONIC).
136 The FpGettimeofday() uses "wall" clock which can go back or forward when
137 synchronization comes more info:
138 https://stackoverflow.com/questions/3832097/how-to-get-the-current-time-in-native-android-code
139 https://developer.android.com/reference/android/os/SystemClock.html
140
141 FreeBSD: also we should use clock_gettime(CLOCK_MONOTONIC,...),
142 see https://discord.com/channels/389676745957310465/389676745957310467/990327113771012126
143
144 Linux: while it seems not necessary in normal circumstances (NTP updates
145 are applied incrementally) still it seems using
146 clock_gettime(CLOCK_MONOTONIC,...) is more reliable.
147 Esp. if admin will change time while the application is running.
148 See
149 https://www.man7.org/linux/man-pages/man2/gettimeofday.2.html
150 https://lwn.net/Articles/23313/
151 }
152
153 type
154 TTimerFrequency = UInt32;
155 const
156 TimerFrequency: TTimerFrequency = 1000000;
157
158 function Timer: TTimerResult;
159 var
160 tp: TimeSpec;
161 begin
162 clock_gettime(CLOCK_MONOTONIC, @tp);
163 Result.Value := QWord(tp.tv_sec) * 1000000 + QWord(tp.tv_nsec div 1000);
164 end;
165
166 {$elseif defined(UNIX)}
167
168 { Fallback Unix implementation using gettimeofday.
169
170 This has a risk of "going back in time",
171 i.e. next FpGettimeofday may return smaller value than the previous one.
172 This is a problem since we use Timer to measure time, so we expect each
173 call to return value >= previous.
174 In fact TimerSeconds will raise Arithmetic Overflow on "(A.Value - B.Value)"
175 when it happens.
176
177 We secure from it using LastTimerValue.
178
179 See
180 https://lwn.net/Articles/23313/
181 https://blog.habets.se/2010/09/gettimeofday-should-never-be-used-to-measure-time.html
182 https://github.com/ThomasHabets/monotonic_clock
183 }
184
185 type
186 TTimerFrequency = UInt32;
187 const
188 TimerFrequency: TTimerFrequency = 1000000;
189
190 var
191 LastTimerValue: QWord;
192
193 function Timer: TTimerResult;
194 var
195 tv: TTimeval;
196 begin
197 {$ifdef FPC}
198 FpGettimeofday(@tv, nil);
199 {$else}
200 Gettimeofday(tv, nil);
201 {$endif}
202
203 { We can fit whole TTimeval inside QWord, no problem. }
204 Result.Value := QWord(tv.tv_sec) * 1000000 + QWord(tv.tv_usec);
205
206 if Result.Value < LastTimerValue then
207 begin
208 WritelnWarning('Time', 'Detected negative time delta, fixing. Better use clock_gettime(CLOCK_MONOTONIC,...) for this platform in CastleTimeUtils.');
209 Result.Value := LastTimerValue;
210 end else
211 LastTimerValue := Result.Value;
212 end;
213
214 {$endif}
215
216 function TimerSeconds(const A, B: TTimerResult): TFloatTime;
217 begin
218 Result := (A.Value - B.Value) / TimerFrequency;
219 end;
220
221 function TTimerResult.ElapsedTime: TFloatTime;
222 begin
223 Result := TimerSeconds(Timer, Self);
224 end;
225
226 function TTimerResult.Initialized: Boolean;
227 begin
228 Result := Value <> 0;
229 end;
230
231 {$endif read_implementation}