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
16 {$include lcoreconfig.inc}
\r
27 tunixtimeint={$ifdef ver100}longint;{$else}int64;{$endif}
\r
30 colorburst=39375000/11; {3579545.4545....}
\r
35 irctime,unixtime:tunixtimeint;
\r
37 settimebias:tunixtimeint;
\r
38 performancecountfreq:extended;
\r
39 btimenowin8:boolean;
\r
41 function irctimefloat:float;
\r
42 function irctimeint:tunixtimeint;
\r
44 //unix timestamp (UTC) float seconds
\r
45 function unixtimefloat:float;
\r
46 function unixtimeint:tunixtimeint;
\r
48 //monotonic float seconds
\r
49 function monotimefloat:float;
\r
51 //monotonic (alias, old function name)
\r
52 function wintimefloat:float;
\r
54 procedure settime(newtime:tunixtimeint);
\r
55 procedure gettimezone;
\r
56 procedure timehandler;
\r
59 function timestring(i:tunixtimeint):string; // Wednesday August 15 2012 -- 16:21:09 +02:00
\r
60 function timestrshort(i:tunixtimeint):string; // Wed Aug 15 16:21:09 2012
\r
61 function timestriso(i:tunixtimeint):string; // 2012-08-15 16:21:09
\r
62 function timestrisoutc(i:float):string; // 2012-08-15T14:21:09.255553Z
\r
64 procedure beginhightimerrate;
\r
65 procedure endhightimerrate;
\r
68 function unixtimefloat_systemtime:float;
\r
71 function oletounixfloat(t:float):float;
\r
72 function oletounix(t:tdatetime):tunixtimeint;
\r
73 function unixtoole(i:float):tdatetime;
\r
76 function mmtimefloat:float;
\r
77 function qpctimefloat:float;
\r
81 procedure gettimeofday(var tv:ttimeval);
\r
86 mmtime_driftavgsize=32;
\r
88 mmtime_warmupcyclelength=15;
\r
90 //this flag is to be set when btime has been running long enough to stabilise
\r
91 warmup_finished:boolean;
\r
93 timefloatbias:float;
\r
95 ticks_freq2:float=0;
\r
96 ticks_freq_known:boolean=false;
\r
97 lastunixtimefloat:float=0;
\r
98 lastsynctime:float=0;
\r
99 lastsyncbias:float=0;
\r
101 mmtime_last:integer=0;
\r
102 mmtime_wrapadd:float;
\r
103 mmtime_lastsyncmm:float=0;
\r
104 mmtime_lastsyncqpc:float=0;
\r
105 mmtime_drift:float=1;
\r
106 mmtime_lastresult:float;
\r
107 mmtime_nextdriftcorrection:float;
\r
108 mmtime_driftavg:array[0..mmtime_driftavgsize] of float;
\r
109 mmtime_synchedqpc:boolean;
\r
111 mmtime_prev_drift:float;
\r
112 mmtime_prev_lastsyncmm:float;
\r
113 mmtime_prev_lastsyncqpc:float;
\r
124 baseunix,unix,unixutil,sockets, {unixutil and sockets needed by unixstuff.inc on some compiler versions}
\r
130 windows,unitsettc,mmsystem,
\r
134 {$include unixstuff.inc}
\r
138 daysdifference=25569;
\r
140 function oletounixfloat(t:float):float;
\r
142 t := (t - daysdifference) * 86400;
\r
146 function oletounix(t:tdatetime):tunixtimeint;
\r
148 result := round(oletounixfloat(t));
\r
151 function unixtoole(i:float):tdatetime;
\r
153 result := ((i)/86400)+daysdifference;
\r
157 highdwordconst=65536.0 * 65536.0;
\r
159 function utrunc(f:float):integer;
\r
160 {converts float to integer, in 32 bits unsigned range}
\r
162 if f >= (highdwordconst/2) then f := f - highdwordconst;
\r
163 result := trunc(f);
\r
166 function uinttofloat(i:integer):float;
\r
167 {converts 32 bits unsigned integer to float}
\r
170 if result < 0 then result := result + highdwordconst;
\r
174 {-----------------------------------------*nix/freepascal code to read time }
\r
176 function unixtimefloat:float;
\r
184 if (sec < 0) then inc(sec,$100000000); //tv_sec is 32 bits
\r
186 result := sec+(tv.tv_usec/1000000);
\r
190 {$define monotimefloat_implemented}
\r
192 CLOCK_MONOTONIC = 1;
\r
194 ptimeval = ^ttimeval;
\r
195 tclock_gettime = function(clk_id: integer; tp: ptimeval): integer; cdecl;
\r
198 librt_handle:pointer;
\r
199 librt_inited:boolean;
\r
200 clock_gettime: tclock_gettime;
\r
202 function monotimefloat:float;
\r
206 if not librt_inited then begin
\r
207 librt_inited := true;
\r
208 clock_gettime := nil;
\r
209 librt_handle := dlopen('librt.so', RTLD_LAZY);
\r
210 if assigned(librt_handle) then begin
\r
211 clock_gettime := dlsym(librt_handle, 'clock_gettime');
\r
214 if assigned(clock_gettime) then begin
\r
215 if clock_gettime(CLOCK_MONOTONIC, @ts) = 0 then begin
\r
216 //note this really returns nanoseconds
\r
217 result := ts.tv_sec + ts.tv_usec / 1000000000.0;
\r
222 result := unixtimefloat;
\r
228 {$ifdef darwin} {mac OS X}
\r
229 {$define monotimefloat_implemented}
\r
232 tmach_timebase_info = packed record
\r
236 pmach_timebase_info = ^tmach_timebase_info;
\r
238 function mach_absolute_time: int64; cdecl; external;
\r
239 function mach_timebase_info(info: pmach_timebase_info): integer; cdecl; external;
\r
242 timebase_info: tmach_timebase_info;
\r
244 function monotimefloat:float;
\r
248 if timebase_info.denom = 0 then begin
\r
249 mach_timebase_info(@timebase_info);
\r
251 i := mach_absolute_time;
\r
252 result := (i * timebase_info.numer div timebase_info.denom) / 1000000000.0;
\r
255 {$endif} {darwin, mac OS X}
\r
258 {$ifndef monotimefloat_implemented} {fallback}
\r
260 function monotimefloat:extended;
\r
262 result := unixtimefloat;
\r
265 {$endif} {monotimefloat fallback}
\r
268 function unixtimeint:tunixtimeint;
\r
276 if (sec < 0) then inc(sec,$100000000); //tv_sec is 32 bits
\r
281 {------------------------------ end of *nix/freepascal section}
\r
284 {------------------------------ windows/delphi code to read time}
\r
287 {simulate gettimeofday on windows so one can always use gettimeofday if preferred}
\r
289 procedure gettimeofday(var tv:ttimeval);
\r
293 e := unixtimefloat;
\r
294 tv.tv_sec := round(int(e));
\r
295 tv.tv_usec := trunc(frac(e)*1000000);
\r
297 if (tv.tv_usec < 0) then tv.tv_usec := 0;
\r
298 if (tv.tv_usec > 999999) then tv.tv_usec := 999999;
\r
303 time float: gettickcount
\r
304 resolution: 9x: ~55 ms NT: 1/64th of a second
\r
305 guarantees: continuous without any jumps
\r
306 frequency base: same as system clock.
\r
308 note: if called more than once per 49.7 days, 32 bits wrapping is compensated for and it keeps going on.
\r
309 note: i handle the timestamp as signed integer, but with the wrap compensation that works as well, and is faster
\r
312 function mmtimefloat:float;
\r
314 wrapduration=highdwordconst * 0.001;
\r
319 i := gettickcount; {timegettime}
\r
320 if i < mmtime_last then begin
\r
321 mmtime_wrapadd := mmtime_wrapadd + wrapduration;
\r
324 result := mmtime_wrapadd + i * 0.001;
\r
326 if (ticks_freq <> 0) and ticks_freq_known then begin
\r
327 {the value we get is rounded to 1 ms, but the ticks are not a multiple of 1 ms
\r
328 this makes the value noisy. use the known ticks frequency to restore the original value}
\r
329 temp := int((result / ticks_freq)+0.5) * ticks_freq;
\r
331 {if the known ticks freq is wrong (can happen), disable the un-rounding behavior
\r
332 this will be a bit less accurate but it prevents problems}
\r
333 if abs(temp - result) > 0.002 then begin
\r
335 end else result := temp;
\r
339 procedure measure_ticks_freq;
\r
345 adjust1,adjust2:cardinal;
\r
346 adjustbool:longbool;
\r
348 if (performancecountfreq = 0) then qpctimefloat;
\r
349 ticks_freq_known := false;
\r
352 repeat g := mmtimefloat until g > f;
\r
355 fillchar(o,sizeof(o),0);
\r
356 o.dwOSVersionInfoSize := sizeof(o);
\r
358 isnt := o.dwPlatformId = VER_PLATFORM_WIN32_NT;
\r
359 { is9x := o.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS;}
\r
362 mmtime_synchedqpc := false;
\r
364 if (isnt and (o.dwMajorVersion >= 5)) then begin
\r
365 {windows 2000 and later: query tick rate from OS in 100 ns units
\r
366 typical rates: XP: 156250 or 100144, windows 7: 156001}
\r
367 if GetSystemTimeAdjustment(adjust1,adjust2,adjustbool) then begin
\r
368 ticks_freq := adjust1 / 10000000.0;
\r
369 ticks_freq_known := true;
\r
370 mmtime_synchedqpc := false;
\r
375 if (performancecountfreq = 1193182) and (f >= 0.050) and (f <= 0.060) then begin
\r
376 ticks_freq_known := true;
\r
377 ticks_freq := 65536 / (colorburst / 3);
\r
378 mmtime_synchedqpc := true;
\r
380 ticks_freq_known := true;
\r
381 if ticks_freq <> 0 then ticks_freq2 := ticks_freq;
\r
382 // writeln(formatfloat('0.000000',ticks_freq));
\r
386 time float: QueryPerformanceCounter
\r
388 guarantees: can have forward jumps depending on hardware. can have forward and backwards jitter on dual core.
\r
389 frequency base: on NT, not the system clock, drifts compared to it.
\r
392 function qpctimefloat:extended;
\r
398 p2:tlargeinteger absolute p;
\r
401 if performancecountfreq = 0 then begin
\r
402 QueryPerformancefrequency(p2);
\r
404 if e < 0 then e := e + highdwordconst;
\r
405 performancecountfreq := ((p.highpart*highdwordconst)+e);
\r
407 queryperformancecounter(p2);
\r
409 if e < 0 then e := e + highdwordconst;
\r
411 result := ((p.highpart*highdwordconst)+e)/performancecountfreq;
\r
415 time float: QPC locked to gettickcount
\r
417 guarantees: continuous without any jumps
\r
418 frequency base: same as system clock.
\r
422 function mmqpctimefloat:float;
\r
428 mm,f,qpc,newdrift:float;
\r
431 { retrycount:integer;}
\r
433 if not ticks_freq_known then measure_ticks_freq;
\r
434 { retrycount := maxretries;}
\r
436 qpc := qpctimefloat;
\r
438 f := (qpc - mmtime_lastsyncqpc) * mmtime_drift + mmtime_lastsyncmm;
\r
439 //writeln('XXXX ',formatfloat('0.000000',qpc-mm));
\r
440 qpcjumped := ((f-mm) > ticks_freq2+margin) or ((f-mm) < -margin);
\r
441 // if qpcjumped then writeln('qpc jumped ',(f-mm));
\r
442 if ((qpc > mmtime_nextdriftcorrection) and not mmtime_synchedqpc) or qpcjumped then begin
\r
444 mmtime_nextdriftcorrection := qpc + 1;
\r
446 mmtime_prev_drift := mmtime_drift;
\r
447 mmtime_prev_lastsyncmm := mmtime_lastsyncmm;
\r
448 mmtime_prev_lastsyncqpc := mmtime_lastsyncqpc;
\r
451 { dec(retrycount);}
\r
453 result := qpctimefloat;
\r
456 if f = mm then result := qpctimefloat;
\r
459 qpc := qpctimefloat;
\r
462 if (qpc > result + 0.0001) then begin
\r
467 if (mmtime_lastsyncqpc <> 0) and not qpcjumped then begin
\r
468 newdrift := (mm - mmtime_lastsyncmm) / (qpc - mmtime_lastsyncqpc);
\r
469 mmtime_drift := newdrift;
\r
470 { writeln('raw drift: ',formatfloat('0.00000000',mmtime_drift));}
\r
471 move(mmtime_driftavg[0],mmtime_driftavg[1],sizeof(mmtime_driftavg[0])*high(mmtime_driftavg));
\r
472 mmtime_driftavg[0] := mmtime_drift;
\r
474 { write('averaging drift ',formatfloat('0.00000000',mmtime_drift),' -> ');}
\r
475 { mmtime_drift := 0;}
\r
477 for a := 0 to high(mmtime_driftavg) do begin
\r
478 if mmtime_driftavg[a] <> 0 then inc(b);
\r
479 { mmtime_drift := mmtime_drift + mmtime_driftavg[a];}
\r
481 { mmtime_drift := mmtime_drift / b;}
\r
483 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
484 mmtime_nextdriftcorrection := qpc + a;
\r
485 if (b >= 2) then warmup_finished := true;
\r
486 { writeln(formatfloat('0.00000000',mmtime_drift));}
\r
487 if mmtime_synchedqpc then mmtime_drift := 1;
\r
490 mmtime_lastsyncqpc := qpc;
\r
491 mmtime_lastsyncmm := mm;
\r
492 { writeln(formatfloat('0.00000000',mmtime_drift));}
\r
497 qpc := qpctimefloat;
\r
499 result := (qpc - mmtime_lastsyncqpc) * mmtime_drift + mmtime_lastsyncmm;
\r
501 {f := (qpc - mmtime_prev_lastsyncqpc) * mmtime_prev_drift + mmtime_prev_lastsyncmm;
\r
503 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
510 if (result < mmtime_lastresult) then result := mmtime_lastresult;
\r
511 mmtime_lastresult := result;
\r
514 { free pascals tsystemtime is incompatible with windows api calls
\r
515 so we declare it ourselves - plugwash
\r
519 TSystemTime = record
\r
527 wMilliseconds: Word;
\r
530 function Date_utc: extended;
\r
532 SystemTime: TSystemTime;
\r
535 GetsystemTime(@SystemTime);
\r
537 GetsystemTime(SystemTime);
\r
539 with SystemTime do Result := EncodeDate(wYear, wMonth, wDay);
\r
542 function Time_utc: extended;
\r
544 SystemTime: TSystemTime;
\r
547 GetsystemTime(@SystemTime);
\r
549 GetsystemTime(SystemTime);
\r
552 Result := EncodeTime(wHour, wMinute, wSecond, wMilliSeconds);
\r
555 function Now_utc: extended;
\r
557 Result := round(Date_utc) + Time_utc;
\r
560 function unixtimefloat_systemtime:float;
\r
562 {result := oletounixfloat(now_utc);}
\r
564 {this method gives exactly the same result with extended precision, but is less sensitive to float rounding in theory}
\r
565 result := oletounixfloat(int(date_utc+0.5))+time_utc*86400;
\r
568 function monotimefloat:extended;
\r
570 result := mmqpctimefloat;
\r
576 GetSystemTimePreciseAsFileTime:procedure(var v:tfiletime); stdcall;
\r
577 win8inited:boolean;
\r
579 procedure initwin8;
\r
584 win8inited := true;
\r
585 dllhandle := loadlibrary('kernel32.dll');
\r
586 if (dllhandle <> 0) then begin
\r
587 GetSystemTimePreciseAsFileTime := getprocaddress(dllhandle,'GetSystemTimePreciseAsFileTime');
\r
592 function unixtimefloat_win8:float;
\r
595 i:int64 absolute ft;
\r
597 GetSystemTimePreciseAsFileTime(ft);
\r
598 {change from windows 1601-01-01 to unix 1970-01-01.
\r
599 use integer math for this, to preserve precision}
\r
600 dec(i, 116444736000000000);
\r
601 result := (i / 10000000);
\r
606 function unixtimefloat:float;
\r
612 if not btimenowin8 then begin
\r
613 if not win8inited then initwin8;
\r
614 if assigned(@GetSystemTimePreciseAsFileTime) then begin
\r
615 result := unixtimefloat_win8;
\r
620 result := monotimefloat+timefloatbias;
\r
621 f := result-unixtimefloat_systemtime;
\r
622 if ((f > ticks_freq2+margin) or (f < -margin)) or (timefloatbias = 0) then begin
\r
623 // writeln('unixtimefloat init');
\r
624 f := unixtimefloat_systemtime;
\r
626 repeat g := unixtimefloat_systemtime; h := monotimefloat until g > f;
\r
628 timefloatbias := g-h;
\r
629 result := unixtimefloat;
\r
632 {for small changes backwards, guarantee no steps backwards}
\r
633 if (result <= lastunixtimefloat) and (result > lastunixtimefloat-1.5) then result := lastunixtimefloat + 0.0000001;
\r
634 lastunixtimefloat := result;
\r
637 function unixtimeint:tunixtimeint;
\r
639 result := trunc(unixtimefloat);
\r
643 {-----------------------------------------------end of platform specific}
\r
645 function wintimefloat:float;
\r
647 result := monotimefloat;
\r
650 function irctimefloat:float;
\r
652 result := unixtimefloat+settimebias;
\r
655 function irctimeint:tunixtimeint;
\r
657 result := unixtimeint+settimebias;
\r
661 procedure settime(newtime:tunixtimeint);
\r
665 a := irctimeint-settimebias;
\r
666 if newtime = 0 then settimebias := 0 else settimebias := newtime-a;
\r
668 irctime := irctimeint;
\r
671 procedure timehandler;
\r
673 if unixtime = 0 then init;
\r
674 unixtime := unixtimeint;
\r
675 irctime := irctimeint;
\r
676 if unixtime and 63 = 0 then begin
\r
677 {update everything, apply timezone changes, clock changes, etc}
\r
679 timefloatbias := 0;
\r
680 unixtime := unixtimeint;
\r
681 irctime := irctimeint;
\r
686 procedure gettimezone;
\r
702 timezone := tzseconds;
\r
705 timezone := (longint(hh) * 3600 + mm * 60 + ss) - (unixtimeint mod 86400);
\r
708 timezone := round((now-now_utc)*86400);
\r
711 while timezone > 43200 do dec(timezone,86400);
\r
712 while timezone < -43200 do inc(timezone,86400);
\r
714 if timezone >= 0 then timezonestr := '+' else timezonestr := '-';
\r
715 l := abs(timezone) div 60;
\r
716 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
719 function timestrshort(i:tunixtimeint):string;
\r
721 weekday:array[0..6] of string[4]=('Thu','Fri','Sat','Sun','Mon','Tue','Wed');
\r
722 month:array[0..11] of string[4]=('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
\r
724 y,m,d,h,min,sec,ms:word;
\r
727 t := unixtoole(i+timezone);
\r
728 decodedate(t,y,m,d);
\r
729 decodetime(t,h,min,sec,ms);
\r
730 result := weekday[(i+timezone) div 86400 mod 7]+' '+month[m-1]+' '+inttostr(d)+' '+
\r
731 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
735 function timestring(i:tunixtimeint):string;
\r
737 weekday:array[0..6] of string[10]=('Thursday','Friday','Saturday','Sunday','Monday','Tuesday','Wednesday');
\r
738 month:array[0..11] of string[10]=('January','February','March','April','May','June','July','August','September','October','November','December');
\r
740 y,m,d,h,min,sec,ms:word;
\r
743 t := unixtoole(i+timezone);
\r
744 decodedate(t,y,m,d);
\r
745 decodetime(t,h,min,sec,ms);
\r
746 result := weekday[(i+timezone) div 86400 mod 7]+' '+month[m-1]+' '+inttostr(d)+' '+inttostr(y)+' -- '+
\r
747 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
751 function timestriso(i:tunixtimeint):string;
\r
753 y,m,d,h,min,sec,ms:word;
\r
756 t := unixtoole(i+timezone);
\r
757 decodedate(t,y,m,d);
\r
758 decodetime(t,h,min,sec,ms);
\r
759 result := inttostr(y)+'-'+inttostr(m div 10)+inttostr(m mod 10)+'-'+inttostr(d div 10)+inttostr(d mod 10)+' '+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
762 function timestrisoutc(i:float):string;
\r
764 y,m,d,h,min,sec,ms:word;
\r
769 decodedate(t,y,m,d);
\r
770 decodetime(t,h,min,sec,ms);
\r
771 result := inttostr(y)+'-'+inttostr(m div 10)+inttostr(m mod 10)+'-'+inttostr(d div 10)+inttostr(d mod 10)+'T'+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
774 result := result + '.'+
\r
775 inttostr(trunc(fr*10) mod 10)+
\r
776 inttostr(trunc(fr*100) mod 10)+
\r
777 inttostr(trunc(fr*1000) mod 10)+
\r
778 inttostr(trunc(fr*10000) mod 10)+
\r
779 inttostr(trunc(fr*100000) mod 10)+
\r
780 inttostr(trunc(fr*1000000) mod 10)+'Z';
\r
784 procedure beginhightimerrate;
\r
786 {$ifdef mswindows}timebeginperiod(1);{$endif}
\r
789 procedure endhightimerrate;
\r
791 {$ifdef mswindows}timeendperiod(1);{$endif}
\r
796 {$ifdef btimehighrate}beginhightimerrate;{$endif}
\r
797 fillchar(mmtime_driftavg,sizeof(mmtime_driftavg),0);
\r
800 unixtime := unixtimeint;
\r
801 irctime := irctimeint;
\r
804 initialization init;
\r