1 { Copyright (C) 2005 Bas Steendijk and Peter Green
\r 
   2   For conditions of distribution and use, see copyright notice in zlib_license.txt
\r 
   3   which is included in the package
\r 
   4   ----------------------------------------------------------------------------- }
\r 
   6 this unit returns unix timestamp with seconds and microseconds (as float)
\r 
   7 works on windows/delphi, and on freepascal on unix.
\r 
  19   colorburst=39375000/11;  {3579545.4545....}
\r 
  23   timezonestr:ansistring;
\r 
  24   irctime,unixtime:integer;
\r 
  26   settimebias:integer;
\r 
  27   performancecountfreq:extended;
\r 
  29 function irctimefloat:float;
\r 
  30 function irctimeint:integer;
\r 
  32 function unixtimefloat:float;
\r 
  33 function unixtimeint:integer;
\r 
  35 function wintimefloat:float;
\r 
  37 procedure settime(newtime:integer);
\r 
  38 procedure gettimezone;
\r 
  39 procedure timehandler;
\r 
  42 function timestring(i:integer):ansistring;
\r 
  43 function timestrshort(i:integer):ansistring;
\r 
  46 function unixtimefloat_systemtime:float;
\r 
  49 function oletounixfloat(t:float):float;
\r 
  50 function oletounix(t:tdatetime):integer;
\r 
  51 function unixtoole(i:integer):tdatetime;
\r 
  54 function mmtimefloat:float;
\r 
  55 function qpctimefloat:float;
\r 
  59   mmtime_driftavgsize=32;
\r 
  61   mmtime_warmupcyclelength=15;
\r 
  63   //this flag is to be set when btime has been running long enough to stabilise
\r 
  64   warmup_finished:boolean;
\r 
  66   timefloatbias:float;
\r 
  68   ticks_freq2:float=0;
\r 
  69   ticks_freq_known:boolean=false;
\r 
  70   lastunixtimefloat:float=0;
\r 
  71   lastsynctime:float=0;
\r 
  72   lastsyncbias:float=0;
\r 
  74   mmtime_last:integer=0;
\r 
  75   mmtime_wrapadd:float;
\r 
  76   mmtime_lastsyncmm:float=0;
\r 
  77   mmtime_lastsyncqpc:float=0;
\r 
  78   mmtime_drift:float=1;
\r 
  79   mmtime_lastresult:float;
\r 
  80   mmtime_nextdriftcorrection:float;
\r 
  81   mmtime_driftavg:array[0..mmtime_driftavgsize] of float;
\r 
  82   mmtime_synchedqpc:boolean;
\r 
  84   mmtime_prev_drift:float;
\r 
  85   mmtime_prev_lastsyncmm:float;
\r 
  86   mmtime_prev_lastsyncqpc:float;
\r 
  99       baseunix,unix,unixutil,sockets, {unixutil and sockets needed by unixstuff.inc on some compiler versions}
\r 
 102     windows,unitsettc,mmsystem,
\r 
 106   {$include unixstuff.inc}
\r 
 110   daysdifference=25569;
\r 
 112 function oletounixfloat(t:float):float;
\r 
 114   t := (t - daysdifference) * 86400;
\r 
 118 function oletounix(t:tdatetime):integer;
\r 
 120   result := trunc(oletounixfloat(t));
\r 
 123 function unixtoole(i:integer):tdatetime;
\r 
 125   result := ((i)/86400)+daysdifference;
\r 
 129   highdwordconst=65536.0 * 65536.0;
\r 
 131 function utrunc(f:float):integer;
\r 
 132 {converts float to integer, in 32 bits unsigned range}
\r 
 134   if f >= (highdwordconst/2) then f := f - highdwordconst;
\r 
 135   result := trunc(f);
\r 
 138 function uinttofloat(i:integer):float;
\r 
 139 {converts 32 bits unsigned integer to float}
\r 
 142   if result < 0 then result := result + highdwordconst;
\r 
 146 {-----------------------------------------*nix/freepascal code to read time }
\r 
 148 function unixtimefloat:float;
\r 
 153   result := tv.tv_sec+(tv.tv_usec/1000000);
\r 
 156 function wintimefloat:extended;
\r 
 158   result := unixtimefloat;
\r 
 161 function unixtimeint:integer;
\r 
 166   result := tv.tv_sec;
\r 
 170 {------------------------------ windows/delphi code to read time}
\r 
 173 time float: gettickcount
\r 
 174 resolution: 9x: ~55 ms NT: 1/64th of a second
\r 
 175 guarantees: continuous without any jumps
\r 
 176 frequency base: same as system clock.
\r 
 178 note: if called more than once per 49.7 days, 32 bits wrapping is compensated for and it keeps going on.
\r 
 179 note: i handle the timestamp as signed integer, but with the wrap compensation that works as well, and is faster
\r 
 182 function mmtimefloat:float;
\r 
 184   wrapduration=highdwordconst * 0.001;
\r 
 188   i := gettickcount; {timegettime}
\r 
 189   if i < mmtime_last then begin
\r 
 190     mmtime_wrapadd := mmtime_wrapadd + wrapduration;
\r 
 193   result := mmtime_wrapadd + i * 0.001;
\r 
 195   if (ticks_freq <> 0) and ticks_freq_known then result := int((result / ticks_freq)+0.5) * ticks_freq; //turn the float into an exact multiple of 1/64th sec to improve accuracy of things using this
\r 
 198 procedure measure_ticks_freq;
\r 
 205   if (performancecountfreq = 0) then qpctimefloat;
\r 
 206   ticks_freq_known := false;
\r 
 209   repeat g := mmtimefloat until g > f;
\r 
 212   fillchar(o,sizeof(o),0);
\r 
 213   o.dwOSVersionInfoSize := sizeof(o);
\r 
 215   isnt := o.dwPlatformId = VER_PLATFORM_WIN32_NT;
\r 
 216   is9x := o.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS;
\r 
 219   mmtime_synchedqpc := false;
\r 
 222   identify mode as: nt64
\r 
 223   QPC rate: either 3579545 or TSC freq
\r 
 224   QPC synched to gettickcount: no
\r 
 225   duration between 2 ticks is constant: yes
\r 
 226   gettickcount tick duration: 64 Hz
\r 
 228   if (f >= 0.014) and (f <= 0.018) and isnt then begin
\r 
 229     ticks_freq_known := true;
\r 
 230     ticks_freq := 1/64;
\r 
 231     mmtime_synchedqpc := false;
\r 
 236   identify mode as: nt100
\r 
 238   QPC synched to gettickcount: yes
\r 
 239   duration between 2 ticks is constant: no?
\r 
 240   gettickcount tick duration: ~99.85 Hz
\r 
 242   if (performancecountfreq = 1193182) and (f >= 0.008) and (f <= 0.012) and isnt then begin
\r 
 243     ticks_freq_known := true;
\r 
 244     ticks_freq2 := 11949 / (colorburst / 3);
\r 
 245    //  ticks_freq2 := 11949 / 1193182;
\r 
 247     {the ticks freq should be very close to the real one but if it's not exact, it will cause drift and correction jumps}
\r 
 248     mmtime_synchedqpc := true;
\r 
 252   if (performancecountfreq = 1193182) and (g >= 0.050) and (g <= 0.060) then begin
\r 
 253     ticks_freq_known := true;
\r 
 254     ticks_freq := 65536 / (colorburst / 3);
\r 
 255     mmtime_synchedqpc := true;
\r 
 257   ticks_freq_known := true;
\r 
 258   if ticks_freq <> 0 then ticks_freq2 := ticks_freq;
\r 
 259 //  writeln(formatfloat('0.000000',ticks_freq));
\r 
 263 time float: QueryPerformanceCounter
\r 
 265 guarantees: can have forward jumps depending on hardware. can have forward and backwards jitter on dual core.
\r 
 266 frequency base: on NT, not the system clock, drifts compared to it.
\r 
 269 function qpctimefloat:extended;
\r 
 275   p2:tlargeinteger absolute p;
\r 
 278   if performancecountfreq = 0 then begin
\r 
 279     QueryPerformancefrequency(p2);
\r 
 281     if e < 0 then e := e + highdwordconst;
\r 
 282     performancecountfreq := ((p.highpart*highdwordconst)+e);
\r 
 284   queryperformancecounter(p2);
\r 
 286   if e < 0 then e := e + highdwordconst;
\r 
 288   result := ((p.highpart*highdwordconst)+e)/performancecountfreq;
\r 
 292 time float: QPC locked to gettickcount
\r 
 294 guarantees: continuous without any jumps
\r 
 295 frequency base: same as system clock.
\r 
 299 function mmqpctimefloat:float;
\r 
 305   mm,f,qpc,newdrift,f1,f2:float;
\r 
 308   retrycount:integer;
\r 
 310   if not ticks_freq_known then measure_ticks_freq;
\r 
 311   retrycount := maxretries;
\r 
 313   qpc := qpctimefloat;
\r 
 315   f := (qpc - mmtime_lastsyncqpc) * mmtime_drift + mmtime_lastsyncmm;
\r 
 316   //writeln('XXXX ',formatfloat('0.000000',qpc-mm));
\r 
 317   qpcjumped := ((f-mm) > ticks_freq2+margin) or ((f-mm) < -margin);
\r 
 318 //  if qpcjumped then writeln('qpc jumped ',(f-mm));
\r 
 319   if ((qpc > mmtime_nextdriftcorrection) and not mmtime_synchedqpc) or qpcjumped then begin
\r 
 321     mmtime_nextdriftcorrection := qpc + 1;
\r 
 323       mmtime_prev_drift := mmtime_drift;
\r 
 324       mmtime_prev_lastsyncmm := mmtime_lastsyncmm;
\r 
 325       mmtime_prev_lastsyncqpc := mmtime_lastsyncqpc;
\r 
 330       result := qpctimefloat;
\r 
 333         if f = mm then result := qpctimefloat;
\r 
 336       qpc := qpctimefloat;
\r 
 339       if (qpc > result + 0.0001) then begin
\r 
 344       if (mmtime_lastsyncqpc <> 0) and not qpcjumped then begin
\r 
 345         newdrift := (mm - mmtime_lastsyncmm) / (qpc - mmtime_lastsyncqpc);
\r 
 346         mmtime_drift := newdrift;
\r 
 347      {   writeln('raw drift: ',formatfloat('0.00000000',mmtime_drift));}
\r 
 348         move(mmtime_driftavg[0],mmtime_driftavg[1],sizeof(mmtime_driftavg[0])*high(mmtime_driftavg));
\r 
 349         mmtime_driftavg[0] := mmtime_drift;
\r 
 351 {        write('averaging drift ',formatfloat('0.00000000',mmtime_drift),' -> ');}
\r 
 352 {        mmtime_drift := 0;}
\r 
 354         for a := 0 to high(mmtime_driftavg) do begin
\r 
 355           if mmtime_driftavg[a] <> 0 then inc(b);
\r 
 356 {          mmtime_drift := mmtime_drift + mmtime_driftavg[a];}
\r 
 358 {        mmtime_drift := mmtime_drift / b;}
\r 
 359         if (b = 1) then a := 5 else if (b = 2) then a := 15 else if (b = 3) then a := 30 else if (b = 4) then a := 60 else if (b = 5) then a := 120 else if (b >= 5) then a := 120;
\r 
 360         mmtime_nextdriftcorrection := qpc + a;
\r 
 361         if (b >= 2) then warmup_finished := true;
\r 
 362 {        writeln(formatfloat('0.00000000',mmtime_drift));}
\r 
 363        if mmtime_synchedqpc then mmtime_drift := 1;
\r 
 366       mmtime_lastsyncqpc := qpc;
\r 
 367       mmtime_lastsyncmm := mm;
\r 
 368   {   writeln(formatfloat('0.00000000',mmtime_drift));}
\r 
 373     qpc := qpctimefloat;
\r 
 375     result := (qpc - mmtime_lastsyncqpc) * mmtime_drift + mmtime_lastsyncmm;
\r 
 376     f := (qpc - mmtime_prev_lastsyncqpc) * mmtime_prev_drift + mmtime_prev_lastsyncmm;
\r 
 379     {writeln('jump ',formatfloat('0.000000',jump),'   drift ',formatfloat('0.00000000',mmtime_drift),' duration ',formatfloat('0.000',(mmtime_lastsyncqpc-mmtime_prev_lastsyncqpc)),' ',formatfloat('0.00000000',jump/(mmtime_lastsyncqpc-mmtime_prev_lastsyncqpc)));}
\r 
 386   if (result < mmtime_lastresult) then result := mmtime_lastresult + 0.000001;
\r 
 387   mmtime_lastresult := result;
\r 
 390 { free pascals tsystemtime is incomaptible with windows api calls
\r 
 391  so we declare it ourselves - plugwash
\r 
 395   TSystemTime = record
\r 
 403      wMilliseconds: Word;
\r 
 406 function Date_utc: extended;
\r 
 408   SystemTime: TSystemTime;
\r 
 411     GetsystemTime(@SystemTime);
\r 
 413     GetsystemTime(SystemTime);
\r 
 415   with SystemTime do Result := EncodeDate(wYear, wMonth, wDay);
\r 
 418 function Time_utc: extended;
\r 
 420   SystemTime: TSystemTime;
\r 
 423     GetsystemTime(@SystemTime);
\r 
 425     GetsystemTime(SystemTime);
\r 
 428     Result := EncodeTime(wHour, wMinute, wSecond, wMilliSeconds);
\r 
 431 function Now_utc: extended;
\r 
 433   Result := round(Date_utc) + Time_utc;
\r 
 436 function unixtimefloat_systemtime:float;
\r 
 438   {result := oletounixfloat(now_utc);}
\r 
 440   {this method gives exactly the same result with extended precision, but is less sensitive to float rounding in theory}
\r 
 441   result := oletounixfloat(int(date_utc+0.5))+time_utc*86400;
\r 
 444 function wintimefloat:extended;
\r 
 446   result := mmqpctimefloat;
\r 
 449 function unixtimefloat:float;
\r 
 455   result := wintimefloat+timefloatbias;
\r 
 456   f := result-unixtimefloat_systemtime;
\r 
 457   if ((f > ticks_freq2+margin) or (f < -margin)) or (timefloatbias = 0) then begin
\r 
 458 //    writeln('unixtimefloat init');
\r 
 459     f := unixtimefloat_systemtime;
\r 
 461     repeat g := unixtimefloat_systemtime; h := wintimefloat until g > f;
\r 
 463     timefloatbias := g-h;
\r 
 464     result := unixtimefloat;
\r 
 467   {for small changes backwards, guarantee no steps backwards}
\r 
 468   if (result <= lastunixtimefloat) and (result > lastunixtimefloat-1.5) then result := lastunixtimefloat + 0.0000001;
\r 
 469   lastunixtimefloat := result;
\r 
 472 function unixtimeint:integer;
\r 
 474   result := trunc(unixtimefloat);
\r 
 478 {-----------------------------------------------end of platform specific}
\r 
 480 function irctimefloat:float;
\r 
 482   result := unixtimefloat+settimebias;
\r 
 485 function irctimeint:integer;
\r 
 487   result := unixtimeint+settimebias;
\r 
 491 procedure settime(newtime:integer);
\r 
 495   a := irctimeint-settimebias;
\r 
 496   if newtime = 0 then settimebias := 0 else settimebias := newtime-a;
\r 
 498   irctime := irctimeint;
\r 
 501 procedure timehandler;
\r 
 503   if unixtime = 0 then init;
\r 
 504   unixtime := unixtimeint;
\r 
 505   irctime := irctimeint;
\r 
 506   if unixtime and 63 = 0 then begin
\r 
 507     {update everything, apply timezone changes, clock changes, etc}
\r 
 509     timefloatbias := 0;
\r 
 510     unixtime := unixtimeint;
\r 
 511     irctime := irctimeint;
\r 
 516 procedure gettimezone;
\r 
 532       timezone := tzseconds;
\r 
 535       timezone := (longint(hh) * 3600 + mm * 60 + ss) - (unixtimeint mod 86400);
\r 
 538   timezone := round((now-now_utc)*86400);
\r 
 541   while timezone > 43200 do dec(timezone,86400);
\r 
 542   while timezone < -43200 do inc(timezone,86400);
\r 
 544   if timezone >= 0 then timezonestr := '+' else timezonestr := '-';
\r 
 545   l := abs(timezone) div 60;
\r 
 546   timezonestr := timezonestr + char(l div 600 mod 10+48)+char(l div 60 mod 10+48)+':'+char(l div 10 mod 6+48)+char(l mod 10+48);
\r 
 549 function timestrshort(i:integer):ansistring;
\r 
 551   weekday:array[0..6] of ansistring =('Thu','Fri','Sat','Sun','Mon','Tue','Wed');
\r 
 552   month:array[0..11] of ansistring =('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
\r 
 554   y,m,d,h,min,sec,ms:word;
\r 
 557   t := unixtoole(i+timezone);
\r 
 558   decodedate(t,y,m,d);
\r 
 559   decodetime(t,h,min,sec,ms);
\r 
 560   result := weekday[(i+timezone) div 86400 mod 7]+' '+month[m-1]+' '+inttostr(d)+' '+
\r 
 561   inttostr(h div 10)+inttostr(h mod 10)+':'+inttostr(min div 10)+inttostr(min mod 10)+':'+inttostr(sec div 10)+inttostr(sec mod 10)+' '+
\r 
 565 function timestring(i:integer):ansistring;
\r 
 567   weekday:array[0..6] of ansistring =('Thursday','Friday','Saturday','Sunday','Monday','Tuesday','Wednesday');
\r 
 568   month:array[0..11] of ansistring =('January','February','March','April','May','June','July','August','September','October','November','December');
\r 
 570   y,m,d,h,min,sec,ms:word;
\r 
 573   t := unixtoole(i+timezone);
\r 
 574   decodedate(t,y,m,d);
\r 
 575   decodetime(t,h,min,sec,ms);
\r 
 576   result := weekday[(i+timezone) div 86400 mod 7]+' '+month[m-1]+' '+inttostr(d)+' '+inttostr(y)+' -- '+
\r 
 577   inttostr(h div 10)+inttostr(h mod 10)+':'+inttostr(min div 10)+inttostr(min mod 10)+':'+inttostr(sec div 10)+inttostr(sec mod 10)+' '+
\r 
 583   {$ifdef win32}timebeginperiod(1);{$endif} //ensure stable unchanging clock
\r 
 584   fillchar(mmtime_driftavg,sizeof(mmtime_driftavg),0);
\r 
 587   unixtime := unixtimeint;
\r 
 588   irctime := irctimeint;
\r 
 591 initialization init;
\r