source: Common/StopWatch.pas

Last change on this file was 571, checked in by chronos, 5 months ago
  • Modified: Code cleanup.
File size: 2.3 KB
Line 
1// Taken from http://delphi.about.com/od/windowsshellapi/a/delphi-high-performance-timer-tstopwatch.htm
2unit StopWatch;
3
4interface
5
6uses
7 {$IFDEF WINDOWS}Windows,{$ENDIF}
8 SysUtils, DateUtils;
9
10type
11 TLargeInteger = Int64;
12
13 TStopWatch = class
14 private
15 FFrequency: TLargeInteger;
16 FIsRunning: Boolean;
17 FIsHighResolution: Boolean;
18 FStartCount, fStopCount: TLargeInteger;
19 procedure SetTickStamp(var Value: TLargeInteger);
20 function GetElapsedTicks: TLargeInteger;
21 function GetElapsedMiliseconds: TLargeInteger;
22 function GetElapsed: string;
23 public
24 constructor Create(const StartOnCreate: Boolean = False) ;
25 procedure Start;
26 procedure Stop;
27 property IsHighResolution: Boolean read FIsHighResolution;
28 property ElapsedTicks: TLargeInteger read GetElapsedTicks;
29 property ElapsedMiliseconds: TLargeInteger read GetElapsedMiliseconds;
30 property Elapsed: string read GetElapsed;
31 property IsRunning: Boolean read FIsRunning;
32 end;
33
34
35implementation
36
37constructor TStopWatch.Create(const StartOnCreate: Boolean = False);
38begin
39 FIsRunning := False;
40
41 {$IFDEF WINDOWS}
42 fIsHighResolution := QueryPerformanceFrequency(fFrequency) ;
43 {$ELSE}
44 FIsHighResolution := False;
45 {$ENDIF}
46 if NOT FIsHighResolution then FFrequency := MSecsPerSec;
47
48 if StartOnCreate then Start;
49end;
50
51function TStopWatch.GetElapsedTicks: TLargeInteger;
52begin
53 Result := FStopCount - FStartCount;
54end;
55
56procedure TStopWatch.SetTickStamp(var Value: TLargeInteger);
57begin
58 if FIsHighResolution then
59 {$IFDEF Windows}
60 QueryPerformanceCounter(Value)
61 {$ELSE}
62 {$ENDIF}
63 else
64 Value := MilliSecondOf(Now);
65end;
66
67function TStopWatch.GetElapsed: string;
68var
69 Elapsed: TDateTime;
70begin
71 Elapsed := ElapsedMiliseconds / MSecsPerSec / SecsPerDay;
72 Result := Format('%d days, %s', [Trunc(Elapsed), FormatDateTime('hh:nn:ss.z', Frac(Elapsed))]) ;
73end;
74
75function TStopWatch.GetElapsedMiliseconds: TLargeInteger;
76begin
77 Result := (MSecsPerSec * (fStopCount - FStartCount)) div FFrequency;
78end;
79
80procedure TStopWatch.Start;
81begin
82 SetTickStamp(FStartCount);
83 FIsRunning := True;
84end;
85
86procedure TStopWatch.Stop;
87begin
88 SetTickStamp(FStopCount);
89 FIsRunning := False;
90end;
91
92end.
Note: See TracBrowser for help on using the repository browser.