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
22 tunixtimeint={$ifdef ver100}longint;{$else}int64;{$endif}
\r
25 colorburst=39375000/11; {3579545.4545....}
\r
30 irctime,unixtime:tunixtimeint;
\r
32 settimebias:tunixtimeint;
\r
33 performancecountfreq:extended;
\r
35 function irctimefloat:float;
\r
36 function irctimeint:tunixtimeint;
\r
38 //unix timestamp (UTC) float seconds
\r
39 function unixtimefloat:float;
\r
40 function unixtimeint:tunixtimeint;
\r
42 //monotonic float seconds
\r
43 function monotimefloat:float;
\r
45 //monotonic (alias, old function name)
\r
46 function wintimefloat:float;
\r
48 procedure settime(newtime:tunixtimeint);
\r
49 procedure gettimezone;
\r
50 procedure timehandler;
\r
53 function timestring(i:tunixtimeint):string;
\r
54 function timestrshort(i:tunixtimeint):string;
\r
57 function unixtimefloat_systemtime:float;
\r
60 function oletounixfloat(t:float):float;
\r
61 function oletounix(t:tdatetime):tunixtimeint;
\r
62 function unixtoole(i:float):tdatetime;
\r
65 function mmtimefloat:float;
\r
66 function qpctimefloat:float;
\r
70 procedure gettimeofday(var tv:ttimeval);
\r
75 mmtime_driftavgsize=32;
\r
77 mmtime_warmupcyclelength=15;
\r
79 //this flag is to be set when btime has been running long enough to stabilise
\r
80 warmup_finished:boolean;
\r
82 timefloatbias:float;
\r
84 ticks_freq2:float=0;
\r
85 ticks_freq_known:boolean=false;
\r
86 lastunixtimefloat:float=0;
\r
87 lastsynctime:float=0;
\r
88 lastsyncbias:float=0;
\r
90 mmtime_last:integer=0;
\r
91 mmtime_wrapadd:float;
\r
92 mmtime_lastsyncmm:float=0;
\r
93 mmtime_lastsyncqpc:float=0;
\r
94 mmtime_drift:float=1;
\r
95 mmtime_lastresult:float;
\r
96 mmtime_nextdriftcorrection:float;
\r
97 mmtime_driftavg:array[0..mmtime_driftavgsize] of float;
\r
98 mmtime_synchedqpc:boolean;
\r
100 mmtime_prev_drift:float;
\r
101 mmtime_prev_lastsyncmm:float;
\r
102 mmtime_prev_lastsyncqpc:float;
\r
115 baseunix,unix,unixutil,sockets, {unixutil and sockets needed by unixstuff.inc on some compiler versions}
\r
121 windows,unitsettc,mmsystem,
\r
125 {$include unixstuff.inc}
\r
129 daysdifference=25569;
\r
131 function oletounixfloat(t:float):float;
\r
133 t := (t - daysdifference) * 86400;
\r
137 function oletounix(t:tdatetime):tunixtimeint;
\r
139 result := trunc(oletounixfloat(t));
\r
142 function unixtoole(i:float):tdatetime;
\r
144 result := ((i)/86400)+daysdifference;
\r
148 highdwordconst=65536.0 * 65536.0;
\r
150 function utrunc(f:float):integer;
\r
151 {converts float to integer, in 32 bits unsigned range}
\r
153 if f >= (highdwordconst/2) then f := f - highdwordconst;
\r
154 result := trunc(f);
\r
157 function uinttofloat(i:integer):float;
\r
158 {converts 32 bits unsigned integer to float}
\r
161 if result < 0 then result := result + highdwordconst;
\r
165 {-----------------------------------------*nix/freepascal code to read time }
\r
167 function unixtimefloat:float;
\r
172 result := tv.tv_sec+(tv.tv_usec/1000000);
\r
176 {$define monotimefloat_implemented}
\r
178 CLOCK_MONOTONIC = 1;
\r
180 ptimeval = ^ttimeval;
\r
181 tclock_gettime = function(clk_id: integer; tp: ptimeval): integer; cdecl;
\r
184 librt_handle:pointer;
\r
185 librt_inited:boolean;
\r
186 clock_gettime: tclock_gettime;
\r
188 function monotimefloat:float;
\r
192 if not librt_inited then begin
\r
193 librt_inited := true;
\r
194 clock_gettime := nil;
\r
195 librt_handle := dlopen('librt.so', RTLD_LAZY);
\r
196 if assigned(librt_handle) then begin
\r
197 clock_gettime := dlsym(librt_handle, 'clock_gettime');
\r
200 if assigned(clock_gettime) then begin
\r
201 if clock_gettime(CLOCK_MONOTONIC, @ts) = 0 then begin
\r
202 //note this really returns nanoseconds
\r
203 result := ts.tv_sec + ts.tv_usec / 1000000000.0;
\r
208 result := unixtimefloat;
\r
214 {$ifdef darwin} {mac OS X}
\r
215 {$define monotimefloat_implemented}
\r
218 tmach_timebase_info = packed record
\r
222 pmach_timebase_info = ^tmach_timebase_info;
\r
224 function mach_absolute_time: int64; cdecl; external;
\r
225 function mach_timebase_info(info: pmach_timebase_info): integer; cdecl; external;
\r
228 timebase_info: tmach_timebase_info;
\r
230 function monotimefloat:float;
\r
234 if timebase_info.denom = 0 then begin
\r
235 mach_timebase_info(@timebase_info);
\r
237 i := mach_absolute_time;
\r
238 result := (i * timebase_info.numer div timebase_info.denom) / 1000000000.0;
\r
241 {$endif} {darwin, mac OS X}
\r
244 {$ifndef monotimefloat_implemented} {fallback}
\r
246 function monotimefloat:extended;
\r
248 result := unixtimefloat;
\r
251 {$endif} {monotimefloat fallback}
\r
254 function unixtimeint:tunixtimeint;
\r
259 result := tv.tv_sec;
\r
262 {------------------------------ end of *nix/freepascal section}
\r
265 {------------------------------ windows/delphi code to read time}
\r
268 {simulate gettimeofday on windows so one can always use gettimeofday if preferred}
\r
270 procedure gettimeofday(var tv:ttimeval);
\r
274 e := unixtimefloat;
\r
275 tv.tv_sec := round(int(e));
\r
276 tv.tv_usec := trunc(frac(e)*1000000);
\r
278 if (tv.tv_usec < 0) then tv.tv_usec := 0;
\r
279 if (tv.tv_usec > 999999) then tv.tv_usec := 999999;
\r
284 time float: gettickcount
\r
285 resolution: 9x: ~55 ms NT: 1/64th of a second
\r
286 guarantees: continuous without any jumps
\r
287 frequency base: same as system clock.
\r
289 note: if called more than once per 49.7 days, 32 bits wrapping is compensated for and it keeps going on.
\r
290 note: i handle the timestamp as signed integer, but with the wrap compensation that works as well, and is faster
\r
293 function mmtimefloat:float;
\r
295 wrapduration=highdwordconst * 0.001;
\r
300 i := gettickcount; {timegettime}
\r
301 if i < mmtime_last then begin
\r
302 mmtime_wrapadd := mmtime_wrapadd + wrapduration;
\r
305 result := mmtime_wrapadd + i * 0.001;
\r
307 if (ticks_freq <> 0) and ticks_freq_known then begin
\r
308 {the value we get is rounded to 1 ms, but the ticks are not a multiple of 1 ms
\r
309 this makes the value noisy. use the known ticks frequency to restore the original value}
\r
310 temp := int((result / ticks_freq)+0.5) * ticks_freq;
\r
312 {if the known ticks freq is wrong (can happen), disable the un-rounding behavior
\r
313 this will be a bit less accurate but it prevents problems}
\r
314 if abs(temp - result) > 0.002 then begin
\r
316 end else result := temp;
\r
320 procedure measure_ticks_freq;
\r
326 adjust1,adjust2:cardinal;
\r
327 adjustbool:longbool;
\r
329 if (performancecountfreq = 0) then qpctimefloat;
\r
330 ticks_freq_known := false;
\r
333 repeat g := mmtimefloat until g > f;
\r
336 fillchar(o,sizeof(o),0);
\r
337 o.dwOSVersionInfoSize := sizeof(o);
\r
339 isnt := o.dwPlatformId = VER_PLATFORM_WIN32_NT;
\r
340 { is9x := o.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS;}
\r
343 mmtime_synchedqpc := false;
\r
345 if (isnt and (o.dwMajorVersion >= 5)) then begin
\r
346 {windows 2000 and later: query tick rate from OS in 100 ns units
\r
347 typical rates: XP: 156250 or 100144, windows 7: 156001}
\r
348 if GetSystemTimeAdjustment(adjust1,adjust2,adjustbool) then begin
\r
349 ticks_freq := adjust1 / 10000000.0;
\r
350 ticks_freq_known := true;
\r
351 mmtime_synchedqpc := false;
\r
356 if (performancecountfreq = 1193182) and (f >= 0.050) and (f <= 0.060) then begin
\r
357 ticks_freq_known := true;
\r
358 ticks_freq := 65536 / (colorburst / 3);
\r
359 mmtime_synchedqpc := true;
\r
361 ticks_freq_known := true;
\r
362 if ticks_freq <> 0 then ticks_freq2 := ticks_freq;
\r
363 // writeln(formatfloat('0.000000',ticks_freq));
\r
367 time float: QueryPerformanceCounter
\r
369 guarantees: can have forward jumps depending on hardware. can have forward and backwards jitter on dual core.
\r
370 frequency base: on NT, not the system clock, drifts compared to it.
\r
373 function qpctimefloat:extended;
\r
379 p2:tlargeinteger absolute p;
\r
382 if performancecountfreq = 0 then begin
\r
383 QueryPerformancefrequency(p2);
\r
385 if e < 0 then e := e + highdwordconst;
\r
386 performancecountfreq := ((p.highpart*highdwordconst)+e);
\r
388 queryperformancecounter(p2);
\r
390 if e < 0 then e := e + highdwordconst;
\r
392 result := ((p.highpart*highdwordconst)+e)/performancecountfreq;
\r
396 time float: QPC locked to gettickcount
\r
398 guarantees: continuous without any jumps
\r
399 frequency base: same as system clock.
\r
403 function mmqpctimefloat:float;
\r
409 mm,f,qpc,newdrift:float;
\r
412 { retrycount:integer;}
\r
414 if not ticks_freq_known then measure_ticks_freq;
\r
415 { retrycount := maxretries;}
\r
417 qpc := qpctimefloat;
\r
419 f := (qpc - mmtime_lastsyncqpc) * mmtime_drift + mmtime_lastsyncmm;
\r
420 //writeln('XXXX ',formatfloat('0.000000',qpc-mm));
\r
421 qpcjumped := ((f-mm) > ticks_freq2+margin) or ((f-mm) < -margin);
\r
422 // if qpcjumped then writeln('qpc jumped ',(f-mm));
\r
423 if ((qpc > mmtime_nextdriftcorrection) and not mmtime_synchedqpc) or qpcjumped then begin
\r
425 mmtime_nextdriftcorrection := qpc + 1;
\r
427 mmtime_prev_drift := mmtime_drift;
\r
428 mmtime_prev_lastsyncmm := mmtime_lastsyncmm;
\r
429 mmtime_prev_lastsyncqpc := mmtime_lastsyncqpc;
\r
432 { dec(retrycount);}
\r
434 result := qpctimefloat;
\r
437 if f = mm then result := qpctimefloat;
\r
440 qpc := qpctimefloat;
\r
443 if (qpc > result + 0.0001) then begin
\r
448 if (mmtime_lastsyncqpc <> 0) and not qpcjumped then begin
\r
449 newdrift := (mm - mmtime_lastsyncmm) / (qpc - mmtime_lastsyncqpc);
\r
450 mmtime_drift := newdrift;
\r
451 { writeln('raw drift: ',formatfloat('0.00000000',mmtime_drift));}
\r
452 move(mmtime_driftavg[0],mmtime_driftavg[1],sizeof(mmtime_driftavg[0])*high(mmtime_driftavg));
\r
453 mmtime_driftavg[0] := mmtime_drift;
\r
455 { write('averaging drift ',formatfloat('0.00000000',mmtime_drift),' -> ');}
\r
456 { mmtime_drift := 0;}
\r
458 for a := 0 to high(mmtime_driftavg) do begin
\r
459 if mmtime_driftavg[a] <> 0 then inc(b);
\r
460 { mmtime_drift := mmtime_drift + mmtime_driftavg[a];}
\r
462 { mmtime_drift := mmtime_drift / b;}
\r
464 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
465 mmtime_nextdriftcorrection := qpc + a;
\r
466 if (b >= 2) then warmup_finished := true;
\r
467 { writeln(formatfloat('0.00000000',mmtime_drift));}
\r
468 if mmtime_synchedqpc then mmtime_drift := 1;
\r
471 mmtime_lastsyncqpc := qpc;
\r
472 mmtime_lastsyncmm := mm;
\r
473 { writeln(formatfloat('0.00000000',mmtime_drift));}
\r
478 qpc := qpctimefloat;
\r
480 result := (qpc - mmtime_lastsyncqpc) * mmtime_drift + mmtime_lastsyncmm;
\r
482 {f := (qpc - mmtime_prev_lastsyncqpc) * mmtime_prev_drift + mmtime_prev_lastsyncmm;
\r
484 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
491 if (result < mmtime_lastresult) then result := mmtime_lastresult;
\r
492 mmtime_lastresult := result;
\r
495 { free pascals tsystemtime is incomaptible with windows api calls
\r
496 so we declare it ourselves - plugwash
\r
500 TSystemTime = record
\r
508 wMilliseconds: Word;
\r
511 function Date_utc: extended;
\r
513 SystemTime: TSystemTime;
\r
516 GetsystemTime(@SystemTime);
\r
518 GetsystemTime(SystemTime);
\r
520 with SystemTime do Result := EncodeDate(wYear, wMonth, wDay);
\r
523 function Time_utc: extended;
\r
525 SystemTime: TSystemTime;
\r
528 GetsystemTime(@SystemTime);
\r
530 GetsystemTime(SystemTime);
\r
533 Result := EncodeTime(wHour, wMinute, wSecond, wMilliSeconds);
\r
536 function Now_utc: extended;
\r
538 Result := round(Date_utc) + Time_utc;
\r
541 function unixtimefloat_systemtime:float;
\r
543 {result := oletounixfloat(now_utc);}
\r
545 {this method gives exactly the same result with extended precision, but is less sensitive to float rounding in theory}
\r
546 result := oletounixfloat(int(date_utc+0.5))+time_utc*86400;
\r
549 function monotimefloat:extended;
\r
551 result := mmqpctimefloat;
\r
554 function unixtimefloat:float;
\r
560 result := monotimefloat+timefloatbias;
\r
561 f := result-unixtimefloat_systemtime;
\r
562 if ((f > ticks_freq2+margin) or (f < -margin)) or (timefloatbias = 0) then begin
\r
563 // writeln('unixtimefloat init');
\r
564 f := unixtimefloat_systemtime;
\r
566 repeat g := unixtimefloat_systemtime; h := monotimefloat until g > f;
\r
568 timefloatbias := g-h;
\r
569 result := unixtimefloat;
\r
572 {for small changes backwards, guarantee no steps backwards}
\r
573 if (result <= lastunixtimefloat) and (result > lastunixtimefloat-1.5) then result := lastunixtimefloat + 0.0000001;
\r
574 lastunixtimefloat := result;
\r
577 function unixtimeint:tunixtimeint;
\r
579 result := trunc(unixtimefloat);
\r
583 {-----------------------------------------------end of platform specific}
\r
585 function wintimefloat:float;
\r
587 result := monotimefloat;
\r
590 function irctimefloat:float;
\r
592 result := unixtimefloat+settimebias;
\r
595 function irctimeint:tunixtimeint;
\r
597 result := unixtimeint+settimebias;
\r
601 procedure settime(newtime:tunixtimeint);
\r
605 a := irctimeint-settimebias;
\r
606 if newtime = 0 then settimebias := 0 else settimebias := newtime-a;
\r
608 irctime := irctimeint;
\r
611 procedure timehandler;
\r
613 if unixtime = 0 then init;
\r
614 unixtime := unixtimeint;
\r
615 irctime := irctimeint;
\r
616 if unixtime and 63 = 0 then begin
\r
617 {update everything, apply timezone changes, clock changes, etc}
\r
619 timefloatbias := 0;
\r
620 unixtime := unixtimeint;
\r
621 irctime := irctimeint;
\r
626 procedure gettimezone;
\r
642 timezone := tzseconds;
\r
645 timezone := (longint(hh) * 3600 + mm * 60 + ss) - (unixtimeint mod 86400);
\r
648 timezone := round((now-now_utc)*86400);
\r
651 while timezone > 43200 do dec(timezone,86400);
\r
652 while timezone < -43200 do inc(timezone,86400);
\r
654 if timezone >= 0 then timezonestr := '+' else timezonestr := '-';
\r
655 l := abs(timezone) div 60;
\r
656 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
659 function timestrshort(i:tunixtimeint):string;
\r
661 weekday:array[0..6] of string[4]=('Thu','Fri','Sat','Sun','Mon','Tue','Wed');
\r
662 month:array[0..11] of string[4]=('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
\r
664 y,m,d,h,min,sec,ms:word;
\r
667 t := unixtoole(i+timezone);
\r
668 decodedate(t,y,m,d);
\r
669 decodetime(t,h,min,sec,ms);
\r
670 result := weekday[(i+timezone) div 86400 mod 7]+' '+month[m-1]+' '+inttostr(d)+' '+
\r
671 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
675 function timestring(i:tunixtimeint):string;
\r
677 weekday:array[0..6] of string[10]=('Thursday','Friday','Saturday','Sunday','Monday','Tuesday','Wednesday');
\r
678 month:array[0..11] of string[10]=('January','February','March','April','May','June','July','August','September','October','November','December');
\r
680 y,m,d,h,min,sec,ms:word;
\r
683 t := unixtoole(i+timezone);
\r
684 decodedate(t,y,m,d);
\r
685 decodetime(t,h,min,sec,ms);
\r
686 result := weekday[(i+timezone) div 86400 mod 7]+' '+month[m-1]+' '+inttostr(d)+' '+inttostr(y)+' -- '+
\r
687 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
693 {$ifdef win32}timebeginperiod(1);{$endif} //ensure stable unchanging clock
\r
694 fillchar(mmtime_driftavg,sizeof(mmtime_driftavg),0);
\r
697 unixtime := unixtimeint;
\r
698 irctime := irctimeint;
\r
701 initialization init;
\r