[Lazarus] How to program with time in milliseconds?

Graeme Geldenhuys mailinglists at geldenhuys.co.uk
Sun May 18 20:10:47 CEST 2014


On 2014-05-15 12:29, Henry Vermaak wrote:
> gettimeofday() is not what you want to use for a timer, though, since it
> will change when someone sets the time on the system.  In that case you
> want to use clock_gettime() with CLOCK_MONOTONIC, or even
> CLOCK_MONOTONIC_RAW (linux only).


And that is exactly what my local copy of EpikTimer does for over a year
alread - just one of many improvements I've made to my copy of
EpikTimer, but sadly never got around to sharing the code (which I'll do
shortly).


----8<-------------8<-------------8<-------------8<-------------8<----

function SystemTicks: TickType;
{$IFDEF Windows}
begin
  QueryPerformanceCounter(Result);
{$ELSE}

const
  CLOCK_MONOTONIC = 1;

        { Experimental, no idea if this works or is implemented correctly }
        function newGetTickCount: Cardinal;
        var
          ts: TTimeSpec;
          i: TickType;
          t: timeval;
        begin
          // use the Posix clock_gettime() call
//          if
do_syscall(syscall_nr_clock_gettime,TSysParam(CLOCK_MONOTONIC),TSysParam(@ts))
// <> 0 then //kernels 2.4.* does not support
          if clock_gettime(CLOCK_MONOTONIC, @ts)=0 then
          begin
            // Use the FPC fallback
            fpgettimeofday(@t,nil);
            // Build a 64 bit microsecond tick from the seconds and
microsecond longints
            Result := (TickType(t.tv_sec) * NanoPerMilli) + t.tv_usec;
            Exit;
          end;
          i := ts.tv_sec;
          i := (i*MilliPerSec) + ts.tv_nsec div NanoPerMilli;
          Result := i;
        end;
begin
  Result := newGetTickCount;
{$ENDIF}
end;
----8<-------------8<-------------8<-------------8<-------------8<----


Regards,
  - Graeme -

-- 
fpGUI Toolkit - a cross-platform GUI toolkit using Free Pascal
http://fpgui.sourceforge.net/




More information about the Lazarus mailing list