1 | // Taken from http://delphi.about.com/od/windowsshellapi/a/delphi-high-performance-timer-tstopwatch.htm
|
---|
2 | unit StopWatch;
|
---|
3 |
|
---|
4 | interface
|
---|
5 |
|
---|
6 | uses Windows, SysUtils, DateUtils;
|
---|
7 |
|
---|
8 | type
|
---|
9 | TStopWatch = class
|
---|
10 | private
|
---|
11 | fFrequency : TLargeInteger;
|
---|
12 | fIsRunning: Boolean;
|
---|
13 | fIsHighResolution: Boolean;
|
---|
14 | fStartCount, fStopCount : TLargeInteger;
|
---|
15 | procedure SetTickStamp(var lInt : TLargeInteger) ;
|
---|
16 | function GetElapsedTicks: TLargeInteger;
|
---|
17 | function GetElapsedMiliseconds: TLargeInteger;
|
---|
18 | function GetElapsed: string;
|
---|
19 | public
|
---|
20 | constructor Create(const startOnCreate : Boolean = False) ;
|
---|
21 | procedure Start;
|
---|
22 | procedure Stop;
|
---|
23 | property IsHighResolution : Boolean read fIsHighResolution;
|
---|
24 | property ElapsedTicks : TLargeInteger read GetElapsedTicks;
|
---|
25 | property ElapsedMiliseconds : TLargeInteger read GetElapsedMiliseconds;
|
---|
26 | property Elapsed : string read GetElapsed;
|
---|
27 | property IsRunning : Boolean read fIsRunning;
|
---|
28 | end;
|
---|
29 |
|
---|
30 | implementation
|
---|
31 |
|
---|
32 | constructor TStopWatch.Create(const startOnCreate : boolean = false) ;
|
---|
33 | begin
|
---|
34 | inherited Create;
|
---|
35 |
|
---|
36 | fIsRunning := False;
|
---|
37 |
|
---|
38 | fIsHighResolution := QueryPerformanceFrequency(fFrequency) ;
|
---|
39 | if NOT fIsHighResolution then fFrequency := MSecsPerSec;
|
---|
40 |
|
---|
41 | if StartOnCreate then Start;
|
---|
42 | end;
|
---|
43 |
|
---|
44 | function TStopWatch.GetElapsedTicks: TLargeInteger;
|
---|
45 | begin
|
---|
46 | Result := fStopCount - fStartCount;
|
---|
47 | end;
|
---|
48 |
|
---|
49 | procedure TStopWatch.SetTickStamp(var lInt : TLargeInteger) ;
|
---|
50 | begin
|
---|
51 | if fIsHighResolution then
|
---|
52 | QueryPerformanceCounter(lInt)
|
---|
53 | else
|
---|
54 | lInt := MilliSecondOf(Now) ;
|
---|
55 | end;
|
---|
56 |
|
---|
57 | function TStopWatch.GetElapsed: string;
|
---|
58 | var
|
---|
59 | dt: TDateTime;
|
---|
60 | begin
|
---|
61 | dt := ElapsedMiliseconds / MSecsPerSec / SecsPerDay;
|
---|
62 | result := Format('%d days, %s', [Trunc(dt), FormatDateTime('hh:nn:ss.z', Frac(dt))]) ;
|
---|
63 | end;
|
---|
64 |
|
---|
65 | function TStopWatch.GetElapsedMiliseconds: TLargeInteger;
|
---|
66 | begin
|
---|
67 | Result := (MSecsPerSec * (fStopCount - fStartCount)) div fFrequency;
|
---|
68 | end;
|
---|
69 |
|
---|
70 | procedure TStopWatch.Start;
|
---|
71 | begin
|
---|
72 | SetTickStamp(fStartCount);
|
---|
73 | fIsRunning := True;
|
---|
74 | end;
|
---|
75 |
|
---|
76 | procedure TStopWatch.Stop;
|
---|
77 | begin
|
---|
78 | SetTickStamp(fStopCount);
|
---|
79 | fIsRunning := False;
|
---|
80 | end;
|
---|
81 |
|
---|
82 | end.
|
---|