home *** CD-ROM | disk | FTP | other *** search
- unit PSTimer;
-
- interface
-
- uses
- Windows,
- SysUtils;
-
- type
- {: Raised when the hardware does not support a high performance timer or
- the elapsed time is queried but the timer has never been started. }
- EPSTimer = class(Exception);
-
- TTime = Double;
-
- {: This class measures elapsed time. }
- TPSTimer = class
- private
- FStopped : Boolean;
- FStartCount : TLargeInteger;
- FStopCount : TLargeInteger;
- private
- function GetTime: TTime;
- public
- {: Creates an stopped timer. }
- constructor Create;
- {: Starts the timer. resetting the elapsed time.
-
- If the timer is already started, it resets the elapsed time to 0.
- }
- procedure Start;
- {: Stops the timer.
-
- If the timer is already stopped, nothing happens.
- }
- procedure Stop;
- {: Returns true if the timer has not been stopped. }
- property IsStopped : boolean read FStopped;
- {: Returns the elapsed time, in seconds.
-
- If the timer is not stopped, it provides the current amount of
- elapsed time.
- }
- property Time : TTime read GetTime;
- {: Returns the timer resolution, in seconds. }
- class function Resolution: TTime;
- end;
-
- {: Creates a new counter at the specified address.
-
- Note that timer must be a variable referring to a timer that has
- not been constructed yet.
- }
- procedure StartCount(var timer : TPSTimer );
-
- {: Returns the elapsed time since StartCount was called by the specified
- timer.
-
- Note that the timer is destroyed, and set to nil.
- }
- function StopCount(var timer : TPSTimer ): TTime;
-
- implementation
-
-
- var
- {: The timer frequency for this machine. }
- FFrequency : TLargeInteger;
- FResolution : TTime;
-
- { TPSTimer }
-
- constructor TPSTimer.Create;
- begin
- FStopped := True;
- end;
-
- class function TPSTimer.Resolution: TTime;
- begin
- Result := FResolution;
- end;
-
- function TPSTimer.GetTime: TTime;
- var
- currentCount : TLargeInteger;
- begin
- if FStopped then
- Result := (FStopCount - FStartCount) / FFrequency
- else begin
- // Check whether the timer is running
- if FStartCount = 0 then
- raise EPSTimer.Create( 'The timer has never been started' );
- QueryPerformanceCounter(currentCount);
- Result := (currentCount - FStartCount) / FFrequency;
- end;
- end;
-
- procedure TPSTimer.Start;
- begin
- QueryPerformanceCounter(FStartCount);
- FStopped := False;
- end;
-
- procedure TPSTimer.Stop;
- begin
- if not FStopped then begin
- QueryPerformanceCounter(FStopCount);
- FStopped := True;
- end;
- end;
-
- procedure StartCount(var timer : TPSTimer );
- begin
- timer := TPSTimer.Create;
- timer.Start;
- end;
-
- function StopCount(var timer : TPSTimer ): TTime;
- begin
- timer.Stop;
- Result := timer.Time;
- FreeAndNil(timer);
- end;
-
- initialization
- if not QueryPerformanceFrequency(FFrequency) then
- raise EPSTimer.Create(
- 'The installed hardware does not support a ' +
- 'high-resolution performance counter' );
- FResolution := 1.0 / FFrequency;
- end.
-