Retrieve time since the system was started

This tip is very simple. Just use standard function GetTickCount and the rest is just elementary mathematics.

The declaration of function GetTickCount can be found in Windows unit (Delphi) and it is external kernel function. It retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days (max. number of DWORD type is 4294967295 milliseconds which is 49.7 days).

function WindowsUpTime: string;
const
  td: integer = 1000 * 60 * 60 * 24;
  th: integer = 1000 * 60 * 60;
  tm: integer = 1000 * 60;
  ts: integer = 1000;
var
  t: longword;
  d, h, m, s: integer;
begin
  t := GetTickCount;
  d := t div td;
  dec(t, d * td);
  h := t div th;
  dec(t, h * th);
  m := t div tm;
  dec(t, m * tm);
  s := t div ts;
  Result := 'Windows startup time: ' + IntToStr(d) + ' days ' + IntToStr(h)+ ' hours ' + IntToStr(m) + ' minutes ' + IntToStr(s)+ ' seconds';
end;

To avoid 49.7 days limitation, you can use GetTickCount64 function, but it’s Windows Vista (Windows Server 2008) only.

Leave a Reply