-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ustopwatch.pas
96 lines (80 loc) · 2.19 KB
/
Ustopwatch.pas
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
unit Ustopwatch;
interface
uses Windows, SysUtils, DateUtils;
type TStopWatch = class
private
fFrequency : TLargeInteger;
fIsRunning: boolean;
fIsHighResolution: boolean;
fStartCount, fStopCount : TLargeInteger;
procedure SetTickStamp(var lInt : TLargeInteger) ;
function GetElapsedTicks: TLargeInteger;
function GetElapsedMilliseconds: TLargeInteger;
function GetElapsed: string;
public
constructor Create(const startOnCreate : boolean = false) ;
procedure Start;
procedure Stop;
property IsHighResolution : boolean read fIsHighResolution;
property ElapsedTicks : TLargeInteger read GetElapsedTicks;
property ElapsedMilliseconds : TLargeInteger read GetElapsedMilliseconds;
property Elapsed : string read GetElapsed;
property IsRunning : boolean read fIsRunning;
end;
implementation
constructor TStopWatch.Create(const startOnCreate : boolean = false) ;
begin
inherited Create;
fIsRunning := false;
fIsHighResolution := QueryPerformanceFrequency(fFrequency) ;
if NOT fIsHighResolution then fFrequency := MSecsPerSec;
if startOnCreate then Start;
end;
function TStopWatch.GetElapsedTicks: TLargeInteger;
begin
result := fStopCount - fStartCount;
end;
procedure TStopWatch.SetTickStamp(var lInt : TLargeInteger) ;
begin
if fIsHighResolution then
QueryPerformanceCounter(lInt)
else
lInt := MilliSecondOf(Now) ;
end;
function TStopWatch.GetElapsed: string;
var
dt : TDateTime;
begin
dt := ElapsedMilliseconds / MSecsPerSec / SecsPerDay;
result := Format('%d days, %s', [trunc(dt), FormatDateTime('hh:nn:ss.z', Frac(dt))]) ;
end;
function TStopWatch.GetElapsedMilliseconds: TLargeInteger;
begin
result := (MSecsPerSec * (fStopCount - fStartCount)) div fFrequency;
end;
procedure TStopWatch.Start;
begin
SetTickStamp(fStartCount) ;
fIsRunning := true;
end;
procedure TStopWatch.Stop;
begin
SetTickStamp(fStopCount) ;
fIsRunning := false;
end;
end.
Here's an example of usage:
var
sw : TStopWatch;
elapsedMilliseconds : cardinal;
begin
sw := TStopWatch.Create() ;
try
sw.Start;
//TimeOutThisFunction()
sw.Stop;
elapsedMilliseconds := sw.ElapsedMilliseconds;
finally
sw.Free;
end;
end;