-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathGpTimestamp.pas
More file actions
879 lines (745 loc) · 28.4 KB
/
Copy pathGpTimestamp.pas
File metadata and controls
879 lines (745 loc) · 28.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
(*:Type-safe timestamp with multiple time source. Prevents mixing incompatible time measurements.
@author Primoz Gabrijelcic (navigator), Claude Code (driver)
@desc <pre>
This software is distributed under the BSD license.
Copyright (c) 2026, Primoz Gabrijelcic
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- The name of the Primoz Gabrijelcic may not be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Author : Primoz Gabrijelcic
Creation date : 2025-11-15
Last modification : 2026-02-18
Version : 1.03
</pre>*)(*
History:
1.03: 2026-02-18
- Added Now method, an alias for FromStopwatch.
1.02: 2025-01-05
- Added HasRemaining method with two overloads for deadline checking.
1.01: 2025-12-15
- TDateTime timestamps are now stored relative to epoch (2025-12-12T00:00:00).
1.0: 2025-12-12
- First public release.
*)
unit GpTimestamp;
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
interface
uses
System.SysUtils;
type
/// <summary>
/// Identifies which clock source is used for time measurement.
/// </summary>
TTimeSource = (
tsNone, // Uninitialized
tsTickCount, // GetTickCount64 - millisecond resolution (Windows only)
tsQueryPerformanceCounter, // QueryPerformanceCounter - high precision (Windows only)
tsTimeGetTime, // DSiTimeGetTime64 - millisecond resolution (Windows only)
tsStopwatch, // TStopwatch - high precision (cross-platform)
tsDateTime, // TDateTime - Delphi date/time (cross-platform)
tsDuration // Pure duration/difference, compatible with all sources
);
/// <summary>
/// Time measurement type that stores the time source and time value.
/// All time values are stored internally as nanoseconds.
/// Prevents mixing times from different sources through operator overloading.
/// </summary>
TGpTimestamp = record
strict private
FValue: Int64; // Time value in nanoseconds
FTimeSource: TTimeSource; // Which clock source was used
procedure CheckCompatible(const other: TGpTimestamp);
{$IFDEF MSWINDOWS}
class function GetPerformanceFrequency: Int64; static; inline;
{$ENDIF}
function GetAsString: string;
procedure SetAsString(const value: string);
public
/// <summary>
/// Alias for FromStopwatch.
/// </summary>
class function Now: TGpTimestamp; overload; static;
/// <summary>
/// Captures current time from TStopwatch (cross-platform).
/// </summary>
class function FromStopwatch: TGpTimestamp; overload; static;
/// <summary>
/// Creates a timestamp from a TStopwatch value.
/// </summary>
class function FromStopwatch(value: Int64): TGpTimestamp; overload; static;
/// <summary>
/// Captures current date/time using NowUTC.
/// Uses tsDateTime source.
/// Values are stored relative to the GpTimestamp epoch (2025-12-12T00:00:00).
/// </summary>
class function FromDateTime: TGpTimestamp; overload; static;
/// <summary>
/// Creates a timestamp from TDateTime value.
/// Uses tsDateTime source.
/// All TDateTime-based timestamps are compatible with each other.
/// Values are stored relative to the GpTimestamp epoch (2025-12-12T00:00:00).
/// </summary>
class function FromDateTime(dt: TDateTime): TGpTimestamp; overload; static;
{$IFDEF MSWINDOWS}
/// <summary>
/// Captures current time from GetTickCount64 (millisecond resolution).
/// </summary>
class function FromTickCount: TGpTimestamp; overload; static;
/// <summary>
/// Creates a timestamp from a TickCount value in milliseconds.
/// </summary>
class function FromTickCount(value_ms: Int64): TGpTimestamp; overload; static;
/// <summary>
/// Captures current time from QueryPerformanceCounter (microsecond+ resolution).
/// </summary>
class function FromQueryPerformanceCounter: TGpTimestamp; overload; static;
/// <summary>
/// Creates a timestamp from a QueryPerformanceCounter value.
/// </summary>
class function FromQueryPerformanceCounter(value: Int64): TGpTimestamp; overload; static;
/// <summary>
/// Captures current time from DSiTimeGetTime64 (millisecond resolution).
/// </summary>
class function FromTimeGetTime: TGpTimestamp; overload; static;
/// <summary>
/// Creates a timestamp from a TimeGetTime value in milliseconds.
/// </summary>
class function FromTimeGetTime(value_ms: Int64): TGpTimestamp; overload; static;
{$ENDIF}
/// <summary>
/// Creates a timestamp with explicit time source and value.
/// </summary>
class function Create(aTimeSource: TTimeSource; aValue_ns: Int64): TGpTimestamp; static;
/// <summary>
/// Creates a duration of the specified number of nanoseconds.
/// Returns a tsDuration timestamp compatible with all other sources.
/// </summary>
class function Nanoseconds(ns: Int64): TGpTimestamp; static;
/// <summary>
/// Creates a duration of the specified number of microseconds.
/// Returns a tsDuration timestamp compatible with all other sources.
/// </summary>
class function Microseconds(us: Int64): TGpTimestamp; static;
/// <summary>
/// Creates a duration of the specified number of milliseconds.
/// Returns a tsDuration timestamp compatible with all other sources.
/// </summary>
class function Milliseconds(ms: Int64): TGpTimestamp; static;
/// <summary>
/// Creates a duration of the specified number of seconds.
/// Supports fractional seconds for sub-second precision.
/// Returns a tsDuration timestamp compatible with all other sources.
/// </summary>
class function Seconds(s: Double): TGpTimestamp; static;
/// <summary>
/// Creates a duration of the specified number of minutes.
/// Returns a tsDuration timestamp compatible with all other sources.
/// </summary>
class function Minutes(m: Int64): TGpTimestamp; static;
/// <summary>
/// Creates a duration of the specified number of hours.
/// Returns a tsDuration timestamp compatible with all other sources.
/// </summary>
class function Hours(h: Int64): TGpTimestamp; static;
/// <summary>
/// Returns a zero timestamp for the specified time source.
/// </summary>
class function Zero(source: TTimeSource): TGpTimestamp; static;
/// <summary>
/// Returns an invalid timestamp (tsNone).
/// </summary>
class function Invalid: TGpTimestamp; static;
/// <summary>
/// Returns the time value in milliseconds.
/// </summary>
function ToMilliseconds: Int64; inline;
/// <summary>
/// Returns the time value in microseconds.
/// </summary>
function ToMicroseconds: Int64; inline;
/// <summary>
/// Returns the time value in nanoseconds.
/// Note: Precision depends on the time source, this is just a unit conversion.
/// </summary>
function ToNanoseconds: Int64; inline;
/// <summary>
/// Returns the time value in seconds as a floating-point number.
/// </summary>
function ToSeconds: Double; inline;
/// <summary>
/// Converts the timestamp to TDateTime.
/// For tsDateTime timestamps, returns the absolute date/time by adding the epoch (2025-12-12T00:00:00).
/// For other timestamp sources, returns a relative time value.
/// </summary>
function ToDateTime: TDateTime;
/// <summary>
/// Returns a human-readable string representation of the timestamp.
/// Format: "1.234567s [QPC]" or "123.456ms [TickCount]"
/// </summary>
function ToString: string;
/// <summary>
/// Returns a detailed debug string with all internal fields.
/// Format: "Source=QPC, Value=1234567890ns"
/// </summary>
function ToDebugString: string;
/// <summary>
/// Returns true if the timestamp is valid (has a time source assigned).
/// </summary>
function IsValid: Boolean; inline;
/// <summary>
/// Returns true if the timestamp represents a duration (tsDuration source).
/// </summary>
function IsDuration: Boolean; inline;
/// <summary>
/// Checks if the specified timeout has elapsed since this timestamp.
/// Automatically uses the same time source for the comparison.
/// Returns True if the timestamp is invalid (TimeSource = tsNone), allowing simple initialization patterns.
/// </summary>
function HasElapsed(timeout_ms: Int64): Boolean; overload;
/// <summary>
/// Checks if the specified duration has elapsed since this timestamp.
/// Automatically uses the same time source for the comparison.
/// The duration parameter must have TimeSource = tsDuration.
/// Returns True if the timestamp is invalid (TimeSource = tsNone), allowing simple initialization patterns.
/// </summary>
function HasElapsed(const duration: TGpTimestamp): Boolean; overload;
/// <summary>
/// Checks if this timestamp is in the future by at least the specified timeout.
/// Automatically uses the same time source for the comparison.
/// Returns False if the timestamp is invalid (TimeSource = tsNone), allowing simple initialization patterns.
/// </summary>
function HasRemaining(timeout_ms: Int64): Boolean; overload;
/// <summary>
/// Checks if this timestamp is in the future by at least the specified duration.
/// Automatically uses the same time source for the comparison.
/// The duration parameter must have TimeSource = tsDuration.
/// Returns False if the timestamp is invalid (TimeSource = tsNone), allowing simple initialization patterns.
/// </summary>
function HasRemaining(const duration: TGpTimestamp): Boolean; overload;
/// <summary>
/// Returns the time elapsed since this timestamp as a duration.
/// Automatically uses the same time source for the current time.
/// Supported for: tsTickCount, tsQueryPerformanceCounter, tsTimeGetTime (Windows), tsStopwatch.
/// Raises EInvalidOpException for unsupported time sources.
/// </summary>
function Elapsed: TGpTimestamp;
/// <summary>
/// Adds two timestamps/durations.
/// timestamp + duration = timestamp (with timestamp's source)
/// duration + timestamp = timestamp (with timestamp's source)
/// duration + duration = duration
/// timestamp + timestamp raises an exception (invalid operation)
/// </summary>
class operator Add(const a, b: TGpTimestamp): TGpTimestamp;
/// <summary>
/// Subtracts two timestamps or durations.
/// timestamp - timestamp = duration (tsDuration source)
/// timestamp - duration = timestamp (preserves timestamp's source)
/// duration - duration = duration
/// duration - timestamp = ERROR (raises EInvalidOpException)
/// Raises an exception if the timestamps have incompatible timebases.
/// </summary>
class operator Subtract(const a, b: TGpTimestamp): TGpTimestamp;
/// <summary>
/// Returns the earlier of two timestamps.
/// Raises an exception if timestamps are incompatible.
/// </summary>
class function Min(const a, b: TGpTimestamp): TGpTimestamp; static;
/// <summary>
/// Returns the later of two timestamps.
/// Raises an exception if timestamps are incompatible.
/// </summary>
class function Max(const a, b: TGpTimestamp): TGpTimestamp; static;
/// <summary>
/// Compares two timestamps. Raises an exception if timebases are incompatible.
/// </summary>
class operator GreaterThan(const a, b: TGpTimestamp): Boolean;
class operator LessThan(const a, b: TGpTimestamp): Boolean;
class operator GreaterThanOrEqual(const a, b: TGpTimestamp): Boolean;
class operator LessThanOrEqual(const a, b: TGpTimestamp): Boolean;
class operator Equal(const a, b: TGpTimestamp): Boolean;
class operator NotEqual(const a, b: TGpTimestamp): Boolean;
/// <summary>
/// The time source used for this timestamp.
/// </summary>
property TimeSource: TTimeSource read FTimeSource;
/// <summary>
/// The time value in nanoseconds.
/// </summary>
property Value_ns: Int64 read FValue;
/// <summary>
/// Serializes/deserializes the timestamp to/from a string representation.
/// Format: "TimeSource|Value_ns"
/// Example: "2|1000000000" represents tsQueryPerformanceCounter with 1 second.
/// </summary>
property AsString: string read GetAsString write SetAsString;
end;
/// <summary>
/// Short alias for TGpTimestamp to reduce verbosity in code.
/// Use for cleaner syntax: _TS_.Milliseconds(500) instead of TGpTimestamp.Milliseconds(500)
/// </summary>
_TS_ = TGpTimestamp;
implementation
uses
System.Diagnostics,
System.DateUtils
{$IFDEF MSWINDOWS}
,Winapi.Windows
,DSiWin32
{$ENDIF}
;
const
// Time conversion constants
CNanosecondsPerMicrosecond = 1000;
CNanosecondsPerMillisecond = 1000000;
CNanosecondsPerSecond = 1000000000;
CNanosecondsPerDay = Int64(86400000000000); // 24 * 60 * 60 * 1000000000
// GpTimestamp epoch for TDateTime conversions: 2025-12-12T00:00:00
// TDateTime values are stored relative to this epoch
CDateTimeEpoch: TDateTime = 45638.0; // EncodeDate(2025, 12, 12) = 45638
{ TGpTimestamp }
procedure TGpTimestamp.CheckCompatible(const other: TGpTimestamp);
begin
// Rule 0: Duration is compatible with everything
if (FTimeSource = tsDuration) or (other.FTimeSource = tsDuration) then
Exit; // Compatible!
// Rule 1: Same source type is always compatible
// (e.g., all FromTickCount calls are compatible)
if (FTimeSource <> tsNone) and (FTimeSource = other.FTimeSource) then
Exit; // Compatible!
// Otherwise: incompatible
raise EInvalidOpException.CreateFmt(
'Cannot mix incompatible time measurements: [Source=%d] vs [Source=%d]',
[Ord(FTimeSource), Ord(other.FTimeSource)]);
end;
{$IFDEF MSWINDOWS}
class function TGpTimestamp.GetPerformanceFrequency: Int64;
begin
QueryPerformanceFrequency(Result);
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
class function TGpTimestamp.FromTickCount: TGpTimestamp;
begin
Result := FromTickCount(GetTickCount64);
end;
class function TGpTimestamp.FromTickCount(value_ms: Int64): TGpTimestamp;
begin
Result.FTimeSource := tsTickCount;
Result.FValue := value_ms * CNanosecondsPerMillisecond;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
class function TGpTimestamp.FromQueryPerformanceCounter: TGpTimestamp;
var
counter: Int64;
begin
QueryPerformanceCounter(counter); // cannot fail, according to the documentation
Result := FromQueryPerformanceCounter(counter);
end;
class function TGpTimestamp.FromQueryPerformanceCounter(value: Int64): TGpTimestamp;
begin
Result.FTimeSource := tsQueryPerformanceCounter;
Result.FValue := Round(value / GetPerformanceFrequency * CNanosecondsPerSecond);
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
class function TGpTimestamp.FromTimeGetTime: TGpTimestamp;
begin
Result := FromTimeGetTime(DSiTimeGetTime64);
end;
class function TGpTimestamp.FromTimeGetTime(value_ms: Int64): TGpTimestamp;
begin
Result.FTimeSource := tsTimeGetTime;
Result.FValue := value_ms * CNanosecondsPerMillisecond;
end;
{$ENDIF}
class function TGpTimestamp.FromStopwatch: TGpTimestamp;
begin
Result := FromStopwatch(TStopwatch.GetTimeStamp);
end;
class function TGpTimestamp.FromStopwatch(value: Int64): TGpTimestamp;
begin
Result.FTimeSource := tsStopwatch;
Result.FValue := Round(value / TStopwatch.Frequency * CNanosecondsPerSecond);
end;
class function TGpTimestamp.FromDateTime: TGpTimestamp;
begin
// Use UTC time
Result := FromDateTime(TTimeZone.Local.ToUniversalTime(System.SysUtils.Now));
end;
class function TGpTimestamp.FromDateTime(dt: TDateTime): TGpTimestamp;
begin
Result.FTimeSource := tsDateTime;
// TDateTime is in days, convert to nanoseconds relative to epoch
Result.FValue := Round((dt - CDateTimeEpoch) * CNanosecondsPerDay);
end;
class function TGpTimestamp.Create(aTimeSource: TTimeSource; aValue_ns: Int64): TGpTimestamp;
begin
Result.FTimeSource := aTimeSource;
Result.FValue := aValue_ns;
end;
class function TGpTimestamp.Nanoseconds(ns: Int64): TGpTimestamp;
begin
Result.FTimeSource := tsDuration;
Result.FValue := ns;
end;
class function TGpTimestamp.Microseconds(us: Int64): TGpTimestamp;
begin
Result.FTimeSource := tsDuration;
Result.FValue := us * CNanosecondsPerMicrosecond;
end;
class function TGpTimestamp.Milliseconds(ms: Int64): TGpTimestamp;
begin
Result.FTimeSource := tsDuration;
Result.FValue := ms * CNanosecondsPerMillisecond;
end;
class function TGpTimestamp.Seconds(s: Double): TGpTimestamp;
begin
Result.FTimeSource := tsDuration;
Result.FValue := Round(s * CNanosecondsPerSecond);
end;
class function TGpTimestamp.Minutes(m: Int64): TGpTimestamp;
begin
Result.FTimeSource := tsDuration;
Result.FValue := m * 60 * CNanosecondsPerSecond;
end;
class function TGpTimestamp.Hours(h: Int64): TGpTimestamp;
begin
Result.FTimeSource := tsDuration;
Result.FValue := h * 3600 * CNanosecondsPerSecond;
end;
class function TGpTimestamp.Zero(source: TTimeSource): TGpTimestamp;
begin
Result.FTimeSource := source;
Result.FValue := 0;
end;
class function TGpTimestamp.Invalid: TGpTimestamp;
begin
Result.FTimeSource := tsNone;
Result.FValue := 0;
end;
class function TGpTimestamp.Min(const a, b: TGpTimestamp): TGpTimestamp;
begin
a.CheckCompatible(b);
if a.FValue <= b.FValue then
Result := a
else
Result := b;
end;
class function TGpTimestamp.Max(const a, b: TGpTimestamp): TGpTimestamp;
begin
a.CheckCompatible(b);
if a.FValue >= b.FValue then
Result := a
else
Result := b;
end;
function TGpTimestamp.ToMilliseconds: Int64;
begin
Result := FValue div CNanosecondsPerMillisecond;
end;
function TGpTimestamp.ToMicroseconds: Int64;
begin
Result := FValue div CNanosecondsPerMicrosecond;
end;
function TGpTimestamp.ToNanoseconds: Int64;
begin
Result := FValue;
end;
function TGpTimestamp.ToSeconds: Double;
begin
Result := FValue / CNanosecondsPerSecond;
end;
function TGpTimestamp.ToDateTime: TDateTime;
begin
// Convert nanoseconds to days (TDateTime unit) and add epoch
Result := (FValue / CNanosecondsPerDay) + CDateTimeEpoch;
end;
function TGpTimestamp.ToString: string;
const
SourceNames: array[TTimeSource] of string = (
'None', 'TickCount', 'QPC', 'TimeGetTime', 'Stopwatch', 'DateTime', 'Duration'
);
var
absValue: Int64;
seconds, milliseconds: Double;
fs: TFormatSettings;
begin
if FTimeSource = tsNone then
Exit('Invalid');
fs := TFormatSettings.Create;
fs.DecimalSeparator := '.';
absValue := System.Abs(FValue);
seconds := absValue / CNanosecondsPerSecond;
milliseconds := absValue / CNanosecondsPerMillisecond;
if absValue >= CNanosecondsPerSecond then // >= 1 second
begin
if FValue < 0 then
Result := Format('-%1.6fs [%s]', [seconds, SourceNames[FTimeSource]], fs)
else
Result := Format('%1.6fs [%s]', [seconds, SourceNames[FTimeSource]], fs);
end
else // < 1 second
begin
if FValue < 0 then
Result := Format('-%1.3fms [%s]', [milliseconds, SourceNames[FTimeSource]], fs)
else
Result := Format('%1.3fms [%s]', [milliseconds, SourceNames[FTimeSource]], fs);
end;
end;
function TGpTimestamp.ToDebugString: string;
const
SourceNames: array[TTimeSource] of string = (
'None', 'TickCount', 'QPC', 'TimeGetTime', 'Stopwatch', 'DateTime', 'Duration'
);
begin
Result := Format('Source=%s, Value=%dns',
[SourceNames[FTimeSource], FValue]);
end;
function TGpTimestamp.IsValid: Boolean;
begin
Result := FTimeSource <> tsNone;
end;
function TGpTimestamp.IsDuration: Boolean;
begin
Result := FTimeSource = tsDuration;
end;
function TGpTimestamp.GetAsString: string;
begin
Result := Format('%d|%d', [Ord(FTimeSource), FValue]);
end;
procedure TGpTimestamp.SetAsString(const value: string);
var
parts: TArray<string>;
timeSource: Integer;
begin
parts := value.Split(['|']);
if Length(parts) <> 2 then
raise EArgumentException.CreateFmt('Invalid timestamp string format: "%s". Expected format: "TimeSource|Value_ns"', [value]);
if not TryStrToInt(parts[0], timeSource) then
raise EArgumentException.CreateFmt('Invalid TimeSource value: "%s"', [parts[0]]);
if (timeSource < Ord(Low(TTimeSource))) or (timeSource > Ord(High(TTimeSource))) then
raise EArgumentException.CreateFmt('TimeSource value out of range: %d', [timeSource]);
FTimeSource := TTimeSource(timeSource);
if not TryStrToInt64(parts[1], FValue) then
raise EArgumentException.CreateFmt('Invalid Value_ns value: "%s"', [parts[1]]);
end;
function TGpTimestamp.HasElapsed(timeout_ms: Int64): Boolean;
var
currentTime: TGpTimestamp;
begin
// Invalid timestamp always returns True (allows simple initialization pattern)
if FTimeSource = tsNone then
Exit(True);
// Get current time from same source
case FTimeSource of
{$IFDEF MSWINDOWS}
tsTickCount: currentTime := FromTickCount;
tsQueryPerformanceCounter: currentTime := FromQueryPerformanceCounter;
tsTimeGetTime: currentTime := FromTimeGetTime;
{$ENDIF}
tsStopwatch: currentTime := FromStopwatch;
tsDateTime: currentTime := FromDateTime;
else
raise EInvalidOpException.CreateFmt(
'HasElapsed not supported for time source: %d', [Ord(FTimeSource)]);
end;
Result := (currentTime.FValue - FValue) >= (timeout_ms * CNanosecondsPerMillisecond);
end;
function TGpTimestamp.HasElapsed(const duration: TGpTimestamp): Boolean;
var
currentTime: TGpTimestamp;
begin
// Verify that duration parameter is actually a duration
if duration.FTimeSource <> tsDuration then
raise EInvalidOpException.Create('HasElapsed duration parameter must have TimeSource = tsDuration');
// Invalid timestamp always returns True (allows simple initialization pattern)
if FTimeSource = tsNone then
Exit(True);
// Get current time from same source
case FTimeSource of
{$IFDEF MSWINDOWS}
tsTickCount: currentTime := FromTickCount;
tsQueryPerformanceCounter: currentTime := FromQueryPerformanceCounter;
tsTimeGetTime: currentTime := FromTimeGetTime;
{$ENDIF}
tsStopwatch: currentTime := FromStopwatch;
tsDateTime: currentTime := FromDateTime;
else
raise EInvalidOpException.CreateFmt(
'HasElapsed not supported for time source: %d', [Ord(FTimeSource)]);
end;
Result := (currentTime.FValue - FValue) >= duration.FValue;
end;
function TGpTimestamp.HasRemaining(timeout_ms: Int64): Boolean;
var
currentTime: TGpTimestamp;
begin
// Invalid timestamp always returns False (nothing remaining if not initialized)
if FTimeSource = tsNone then
Exit(False);
// Get current time from same source
case FTimeSource of
{$IFDEF MSWINDOWS}
tsTickCount: currentTime := FromTickCount;
tsQueryPerformanceCounter: currentTime := FromQueryPerformanceCounter;
tsTimeGetTime: currentTime := FromTimeGetTime;
{$ENDIF}
tsStopwatch: currentTime := FromStopwatch;
tsDateTime: currentTime := FromDateTime;
else
raise EInvalidOpException.CreateFmt(
'HasRemaining not supported for time source: %d', [Ord(FTimeSource)]);
end;
Result := (FValue - currentTime.FValue) >= (timeout_ms * CNanosecondsPerMillisecond);
end;
function TGpTimestamp.HasRemaining(const duration: TGpTimestamp): Boolean;
var
currentTime: TGpTimestamp;
begin
// Verify that duration parameter is actually a duration
if duration.FTimeSource <> tsDuration then
raise EInvalidOpException.Create('HasRemaining duration parameter must have TimeSource = tsDuration');
// Invalid timestamp always returns False (nothing remaining if not initialized)
if FTimeSource = tsNone then
Exit(False);
// Get current time from same source
case FTimeSource of
{$IFDEF MSWINDOWS}
tsTickCount: currentTime := FromTickCount;
tsQueryPerformanceCounter: currentTime := FromQueryPerformanceCounter;
tsTimeGetTime: currentTime := FromTimeGetTime;
{$ENDIF}
tsStopwatch: currentTime := FromStopwatch;
tsDateTime: currentTime := FromDateTime;
else
raise EInvalidOpException.CreateFmt(
'HasRemaining not supported for time source: %d', [Ord(FTimeSource)]);
end;
Result := (FValue - currentTime.FValue) >= duration.FValue;
end;
function TGpTimestamp.Elapsed: TGpTimestamp;
var
currentTime: TGpTimestamp;
begin
// Get current time from same source
case FTimeSource of
{$IFDEF MSWINDOWS}
tsTickCount: currentTime := FromTickCount;
tsQueryPerformanceCounter: currentTime := FromQueryPerformanceCounter;
tsTimeGetTime: currentTime := FromTimeGetTime;
{$ENDIF}
tsStopwatch: currentTime := FromStopwatch;
tsDateTime: currentTime := FromDateTime;
else
raise EInvalidOpException.CreateFmt(
'Elapsed not supported for time source: %d', [Ord(FTimeSource)]);
end;
// Return duration (currentTime - self)
Result := currentTime - Self;
end;
class function TGpTimestamp.Now: TGpTimestamp;
begin
Result := FromStopwatch;
end;
class operator TGpTimestamp.Subtract(const a, b: TGpTimestamp): TGpTimestamp;
begin
a.CheckCompatible(b);
// duration - timestamp is invalid
if (a.FTimeSource = tsDuration) and (b.FTimeSource <> tsDuration) then
raise EInvalidOpException.Create('Cannot subtract timestamp from duration');
// timestamp - timestamp = duration
if (a.FTimeSource <> tsDuration) and (b.FTimeSource <> tsDuration) then
begin
Result.FTimeSource := tsDuration;
Result.FValue := a.FValue - b.FValue;
end
// duration - duration = duration
else if (a.FTimeSource = tsDuration) and (b.FTimeSource = tsDuration) then
begin
Result.FTimeSource := tsDuration;
Result.FValue := a.FValue - b.FValue;
end
// timestamp - duration = timestamp (preserve timestamp's source)
else
begin
Result := a;
Result.FValue := a.FValue - b.FValue;
end;
end;
class operator TGpTimestamp.Add(const a, b: TGpTimestamp): TGpTimestamp;
begin
a.CheckCompatible(b);
// timestamp + timestamp is invalid
if (a.FTimeSource <> tsDuration) and (b.FTimeSource <> tsDuration) then
raise EInvalidOpException.Create('Cannot add two timestamps; only timestamp + duration is valid');
// duration + duration = duration
if (a.FTimeSource = tsDuration) and (b.FTimeSource = tsDuration) then
begin
Result.FTimeSource := tsDuration;
Result.FValue := a.FValue + b.FValue;
end
// timestamp + duration = timestamp (preserve timestamp's source)
else if a.FTimeSource <> tsDuration then
begin
Result := a;
Result.FValue := a.FValue + b.FValue;
end
// duration + timestamp = timestamp (preserve timestamp's source)
else
begin
Result := b;
Result.FValue := a.FValue + b.FValue;
end;
end;
class operator TGpTimestamp.GreaterThan(const a, b: TGpTimestamp): Boolean;
begin
a.CheckCompatible(b);
Result := a.FValue > b.FValue;
end;
class operator TGpTimestamp.LessThan(const a, b: TGpTimestamp): Boolean;
begin
a.CheckCompatible(b);
Result := a.FValue < b.FValue;
end;
class operator TGpTimestamp.GreaterThanOrEqual(const a, b: TGpTimestamp): Boolean;
begin
a.CheckCompatible(b);
Result := a.FValue >= b.FValue;
end;
class operator TGpTimestamp.LessThanOrEqual(const a, b: TGpTimestamp): Boolean;
begin
a.CheckCompatible(b);
Result := a.FValue <= b.FValue;
end;
class operator TGpTimestamp.Equal(const a, b: TGpTimestamp): Boolean;
begin
a.CheckCompatible(b);
Result := a.FValue = b.FValue;
end;
class operator TGpTimestamp.NotEqual(const a, b: TGpTimestamp): Boolean;
begin
a.CheckCompatible(b);
Result := a.FValue <> b.FValue;
end;
end.