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 {$ifdef linux}linux,{$endif} //for clock_gettime
\r
125 {$ifdef freebsd}freebsd,{$endif} //for clock_gettime
\r
126 baseunix,unix,unixutil,sockets, {unixutil and sockets needed by unixstuff.inc on some compiler versions}
\r
129 windows,unitsettc,mmsystem,
\r
133 {$include unixstuff.inc}
\r
137 daysdifference=25569;
\r
139 function oletounixfloat(t:float):float;
\r
141 t := (t - daysdifference) * 86400;
\r
145 function oletounix(t:tdatetime):tunixtimeint;
\r
147 result := round(oletounixfloat(t));
\r
150 function unixtoole(i:float):tdatetime;
\r
152 result := ((i)/86400)+daysdifference;
\r
156 highdwordconst=65536.0 * 65536.0;
\r
158 function utrunc(f:float):integer;
\r
159 {converts float to integer, in 32 bits unsigned range}
\r
161 if f >= (highdwordconst/2) then f := f - highdwordconst;
\r
162 result := trunc(f);
\r
165 function uinttofloat(i:integer):float;
\r
166 {converts 32 bits unsigned integer to float}
\r
169 if result < 0 then result := result + highdwordconst;
\r
173 {-----------------------------------------*nix/freepascal code to read time }
\r
175 function unixtimefloat:float;
\r
183 if (sec < -1) then inc(sec,$100000000); //tv_sec is 32 bits. allow -1 for invalid result
\r
185 result := sec+(tv.tv_usec/1000000);
\r
188 {$ifdef linux}{$define have_clock_gettime}{$endif}
\r
189 {$ifdef freebsd}{$define have_clock_gettime}{$endif}
\r
191 {$ifdef have_clock_gettime}
\r
192 {$define monotimefloat_implemented}
\r
194 function monotimefloat:float;
\r
198 if clock_gettime(CLOCK_MONOTONIC, @ts) = 0 then begin
\r
199 //note this really returns nanoseconds
\r
200 result := ts.tv_sec + ts.tv_nsec / 1000000000.0;
\r
204 result := unixtimefloat;
\r
210 {$ifdef darwin} {mac OS X}
\r
211 {$define monotimefloat_implemented}
\r
214 tmach_timebase_info = packed record
\r
218 pmach_timebase_info = ^tmach_timebase_info;
\r
220 function mach_absolute_time: int64; cdecl; external;
\r
221 function mach_timebase_info(info: pmach_timebase_info): integer; cdecl; external;
\r
224 timebase_info: tmach_timebase_info;
\r
226 function monotimefloat:float;
\r
230 if timebase_info.denom = 0 then begin
\r
231 mach_timebase_info(@timebase_info);
\r
233 i := mach_absolute_time;
\r
234 result := (i * timebase_info.numer div timebase_info.denom) / 1000000000.0;
\r
237 {$endif} {darwin, mac OS X}
\r
240 {$ifndef monotimefloat_implemented} {fallback}
\r
242 function monotimefloat:extended;
\r
244 result := unixtimefloat;
\r
247 {$endif} {monotimefloat fallback}
\r
250 function unixtimeint:tunixtimeint;
\r
258 if (sec < 0) then inc(sec,$100000000); //tv_sec is 32 bits
\r
263 {------------------------------ end of *nix/freepascal section}
\r
266 {------------------------------ windows/delphi code to read time}
\r
269 {simulate gettimeofday on windows so one can always use gettimeofday if preferred}
\r
271 procedure gettimeofday(var tv:ttimeval);
\r
275 e := unixtimefloat;
\r
276 tv.tv_sec := round(int(e));
\r
277 tv.tv_usec := trunc(frac(e)*1000000);
\r
279 if (tv.tv_usec < 0) then tv.tv_usec := 0;
\r
280 if (tv.tv_usec > 999999) then tv.tv_usec := 999999;
\r
285 time float: gettickcount
\r
286 resolution: 9x: ~55 ms NT: 1/64th of a second
\r
287 guarantees: continuous without any jumps
\r
288 frequency base: same as system clock.
\r
290 note: if called more than once per 49.7 days, 32 bits wrapping is compensated for and it keeps going on.
\r
291 note: i handle the timestamp as signed integer, but with the wrap compensation that works as well, and is faster
\r
294 function mmtimefloat:float;
\r
296 wrapduration=highdwordconst * 0.001;
\r
301 i := gettickcount; {timegettime}
\r
302 if i < mmtime_last then begin
\r
303 mmtime_wrapadd := mmtime_wrapadd + wrapduration;
\r
306 result := mmtime_wrapadd + i * 0.001;
\r
308 if (ticks_freq <> 0) and ticks_freq_known then begin
\r
309 {the value we get is rounded to 1 ms, but the ticks are not a multiple of 1 ms
\r
310 this makes the value noisy. use the known ticks frequency to restore the original value}
\r
311 temp := int((result / ticks_freq)+0.5) * ticks_freq;
\r
313 {if the known ticks freq is wrong (can happen), disable the un-rounding behavior
\r
314 this will be a bit less accurate but it prevents problems}
\r
315 if abs(temp - result) > 0.002 then begin
\r
317 end else result := temp;
\r
321 procedure measure_ticks_freq;
\r
327 adjust1,adjust2:cardinal;
\r
328 adjustbool:longbool;
\r
330 if (performancecountfreq = 0) then qpctimefloat;
\r
331 ticks_freq_known := false;
\r
334 repeat g := mmtimefloat until g > f;
\r
337 fillchar(o,sizeof(o),0);
\r
338 o.dwOSVersionInfoSize := sizeof(o);
\r
340 isnt := o.dwPlatformId = VER_PLATFORM_WIN32_NT;
\r
341 { is9x := o.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS;}
\r
344 mmtime_synchedqpc := false;
\r
346 if (isnt and (o.dwMajorVersion >= 5)) then begin
\r
347 {windows 2000 and later: query tick rate from OS in 100 ns units
\r
348 typical rates: XP: 156250 or 100144, windows 7: 156001}
\r
349 if GetSystemTimeAdjustment(adjust1,adjust2,adjustbool) then begin
\r
350 ticks_freq := adjust1 / 10000000.0;
\r
351 ticks_freq_known := true;
\r
352 mmtime_synchedqpc := false;
\r
357 if (performancecountfreq = 1193182) and (f >= 0.050) and (f <= 0.060) then begin
\r
358 ticks_freq_known := true;
\r
359 ticks_freq := 65536 / (colorburst / 3);
\r
360 mmtime_synchedqpc := true;
\r
362 ticks_freq_known := true;
\r
363 if ticks_freq <> 0 then ticks_freq2 := ticks_freq;
\r
364 // writeln(formatfloat('0.000000',ticks_freq));
\r
368 time float: QueryPerformanceCounter
\r
370 guarantees: can have forward jumps depending on hardware. can have forward and backwards jitter on dual core.
\r
371 frequency base: on NT, not the system clock, drifts compared to it.
\r
374 function qpctimefloat:extended;
\r
380 p2:tlargeinteger absolute p;
\r
383 if performancecountfreq = 0 then begin
\r
384 QueryPerformancefrequency(p2);
\r
386 if e < 0 then e := e + highdwordconst;
\r
387 performancecountfreq := ((p.highpart*highdwordconst)+e);
\r
389 queryperformancecounter(p2);
\r
391 if e < 0 then e := e + highdwordconst;
\r
393 result := ((p.highpart*highdwordconst)+e)/performancecountfreq;
\r
397 time float: QPC locked to gettickcount
\r
399 guarantees: continuous without any jumps
\r
400 frequency base: same as system clock.
\r
404 function mmqpctimefloat:float;
\r
410 mm,f,qpc,newdrift:float;
\r
413 { retrycount:integer;}
\r
415 if not ticks_freq_known then measure_ticks_freq;
\r
416 { retrycount := maxretries;}
\r
418 qpc := qpctimefloat;
\r
420 f := (qpc - mmtime_lastsyncqpc) * mmtime_drift + mmtime_lastsyncmm;
\r
421 //writeln('XXXX ',formatfloat('0.000000',qpc-mm));
\r
422 qpcjumped := ((f-mm) > ticks_freq2+margin) or ((f-mm) < -margin);
\r
423 // if qpcjumped then writeln('qpc jumped ',(f-mm));
\r
424 if ((qpc > mmtime_nextdriftcorrection) and not mmtime_synchedqpc) or qpcjumped then begin
\r
426 mmtime_nextdriftcorrection := qpc + 1;
\r
428 mmtime_prev_drift := mmtime_drift;
\r
429 mmtime_prev_lastsyncmm := mmtime_lastsyncmm;
\r
430 mmtime_prev_lastsyncqpc := mmtime_lastsyncqpc;
\r
433 { dec(retrycount);}
\r
435 result := qpctimefloat;
\r
438 if f = mm then result := qpctimefloat;
\r
441 qpc := qpctimefloat;
\r
444 if (qpc > result + 0.0001) then begin
\r
449 if (mmtime_lastsyncqpc <> 0) and not qpcjumped then begin
\r
450 newdrift := (mm - mmtime_lastsyncmm) / (qpc - mmtime_lastsyncqpc);
\r
451 mmtime_drift := newdrift;
\r
452 { writeln('raw drift: ',formatfloat('0.00000000',mmtime_drift));}
\r
453 move(mmtime_driftavg[0],mmtime_driftavg[1],sizeof(mmtime_driftavg[0])*high(mmtime_driftavg));
\r
454 mmtime_driftavg[0] := mmtime_drift;
\r
456 { write('averaging drift ',formatfloat('0.00000000',mmtime_drift),' -> ');}
\r
457 { mmtime_drift := 0;}
\r
459 for a := 0 to high(mmtime_driftavg) do begin
\r
460 if mmtime_driftavg[a] <> 0 then inc(b);
\r
461 { mmtime_drift := mmtime_drift + mmtime_driftavg[a];}
\r
463 { mmtime_drift := mmtime_drift / b;}
\r
465 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
466 mmtime_nextdriftcorrection := qpc + a;
\r
467 if (b >= 2) then warmup_finished := true;
\r
468 { writeln(formatfloat('0.00000000',mmtime_drift));}
\r
469 if mmtime_synchedqpc then mmtime_drift := 1;
\r
472 mmtime_lastsyncqpc := qpc;
\r
473 mmtime_lastsyncmm := mm;
\r
474 { writeln(formatfloat('0.00000000',mmtime_drift));}
\r
479 qpc := qpctimefloat;
\r
481 result := (qpc - mmtime_lastsyncqpc) * mmtime_drift + mmtime_lastsyncmm;
\r
483 {f := (qpc - mmtime_prev_lastsyncqpc) * mmtime_prev_drift + mmtime_prev_lastsyncmm;
\r
485 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
492 if (result < mmtime_lastresult) then result := mmtime_lastresult;
\r
493 mmtime_lastresult := result;
\r
496 { free pascals tsystemtime is incompatible with windows api calls
\r
497 so we declare it ourselves - plugwash
\r
501 TSystemTime = record
\r
509 wMilliseconds: Word;
\r
512 function Date_utc: extended;
\r
514 SystemTime: TSystemTime;
\r
517 GetsystemTime(@SystemTime);
\r
519 GetsystemTime(SystemTime);
\r
521 with SystemTime do Result := EncodeDate(wYear, wMonth, wDay);
\r
524 function Time_utc: extended;
\r
526 SystemTime: TSystemTime;
\r
529 GetsystemTime(@SystemTime);
\r
531 GetsystemTime(SystemTime);
\r
534 Result := EncodeTime(wHour, wMinute, wSecond, wMilliSeconds);
\r
537 function Now_utc: extended;
\r
539 Result := round(Date_utc) + Time_utc;
\r
542 function unixtimefloat_systemtime:float;
\r
544 {result := oletounixfloat(now_utc);}
\r
546 {this method gives exactly the same result with extended precision, but is less sensitive to float rounding in theory}
\r
547 result := oletounixfloat(int(date_utc+0.5))+time_utc*86400;
\r
550 function monotimefloat:extended;
\r
552 result := mmqpctimefloat;
\r
558 GetSystemTimePreciseAsFileTime:procedure(var v:tfiletime); stdcall;
\r
559 win8inited:boolean;
\r
561 procedure initwin8;
\r
566 win8inited := true;
\r
567 dllhandle := loadlibrary('kernel32.dll');
\r
568 if (dllhandle <> 0) then begin
\r
569 GetSystemTimePreciseAsFileTime := getprocaddress(dllhandle,'GetSystemTimePreciseAsFileTime');
\r
574 function unixtimefloat_win8:float;
\r
577 i:int64 absolute ft;
\r
579 GetSystemTimePreciseAsFileTime(ft);
\r
580 {change from windows 1601-01-01 to unix 1970-01-01.
\r
581 use integer math for this, to preserve precision}
\r
582 dec(i, 116444736000000000);
\r
583 result := (i / 10000000);
\r
588 function unixtimefloat:float;
\r
594 if not btimenowin8 then begin
\r
595 if not win8inited then initwin8;
\r
596 if assigned(@GetSystemTimePreciseAsFileTime) then begin
\r
597 result := unixtimefloat_win8;
\r
602 result := monotimefloat+timefloatbias;
\r
603 f := result-unixtimefloat_systemtime;
\r
604 if ((f > ticks_freq2+margin) or (f < -margin)) or (timefloatbias = 0) then begin
\r
605 // writeln('unixtimefloat init');
\r
606 f := unixtimefloat_systemtime;
\r
608 repeat g := unixtimefloat_systemtime; h := monotimefloat until g > f;
\r
610 timefloatbias := g-h;
\r
611 result := unixtimefloat;
\r
614 {for small changes backwards, guarantee no steps backwards}
\r
615 if (result <= lastunixtimefloat) and (result > lastunixtimefloat-1.5) then result := lastunixtimefloat + 0.0000001;
\r
616 lastunixtimefloat := result;
\r
619 function unixtimeint:tunixtimeint;
\r
621 result := trunc(unixtimefloat);
\r
625 {-----------------------------------------------end of platform specific}
\r
627 function wintimefloat:float;
\r
629 result := monotimefloat;
\r
632 function irctimefloat:float;
\r
634 result := unixtimefloat+settimebias;
\r
637 function irctimeint:tunixtimeint;
\r
639 result := unixtimeint+settimebias;
\r
643 procedure settime(newtime:tunixtimeint);
\r
647 a := irctimeint-settimebias;
\r
648 if newtime = 0 then settimebias := 0 else settimebias := newtime-a;
\r
650 irctime := irctimeint;
\r
653 procedure timehandler;
\r
655 if unixtime = 0 then init;
\r
656 unixtime := unixtimeint;
\r
657 irctime := irctimeint;
\r
658 if unixtime and 63 = 0 then begin
\r
659 {update everything, apply timezone changes, clock changes, etc}
\r
661 timefloatbias := 0;
\r
662 unixtime := unixtimeint;
\r
663 irctime := irctimeint;
\r
668 procedure gettimezone;
\r
684 timezone := tzseconds;
\r
687 timezone := (longint(hh) * 3600 + mm * 60 + ss) - (unixtimeint mod 86400);
\r
690 timezone := round((now-now_utc)*86400);
\r
693 while timezone > 43200 do dec(timezone,86400);
\r
694 while timezone < -43200 do inc(timezone,86400);
\r
696 if timezone >= 0 then timezonestr := '+' else timezonestr := '-';
\r
697 l := abs(timezone) div 60;
\r
698 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
701 function timestrshort(i:tunixtimeint):string;
\r
703 weekday:array[0..6] of string[4]=('Thu','Fri','Sat','Sun','Mon','Tue','Wed');
\r
704 month:array[0..11] of string[4]=('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
\r
706 y,m,d,h,min,sec,ms:word;
\r
709 t := unixtoole(i+timezone);
\r
710 decodedate(t,y,m,d);
\r
711 decodetime(t,h,min,sec,ms);
\r
712 result := weekday[(i+timezone) div 86400 mod 7]+' '+month[m-1]+' '+inttostr(d)+' '+
\r
713 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
717 function timestring(i:tunixtimeint):string;
\r
719 weekday:array[0..6] of string[10]=('Thursday','Friday','Saturday','Sunday','Monday','Tuesday','Wednesday');
\r
720 month:array[0..11] of string[10]=('January','February','March','April','May','June','July','August','September','October','November','December');
\r
722 y,m,d,h,min,sec,ms:word;
\r
725 t := unixtoole(i+timezone);
\r
726 decodedate(t,y,m,d);
\r
727 decodetime(t,h,min,sec,ms);
\r
728 result := weekday[(i+timezone) div 86400 mod 7]+' '+month[m-1]+' '+inttostr(d)+' '+inttostr(y)+' -- '+
\r
729 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
733 function timestriso(i:tunixtimeint):string;
\r
735 y,m,d,h,min,sec,ms:word;
\r
738 t := unixtoole(i+timezone);
\r
739 decodedate(t,y,m,d);
\r
740 decodetime(t,h,min,sec,ms);
\r
741 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
744 function timestrisoutc(i:float):string;
\r
746 y,m,d,h,min,sec,ms:word;
\r
751 decodedate(t,y,m,d);
\r
752 decodetime(t,h,min,sec,ms);
\r
753 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
756 result := result + '.'+
\r
757 inttostr(trunc(fr*10) mod 10)+
\r
758 inttostr(trunc(fr*100) mod 10)+
\r
759 inttostr(trunc(fr*1000) mod 10)+
\r
760 inttostr(trunc(fr*10000) mod 10)+
\r
761 inttostr(trunc(fr*100000) mod 10)+
\r
762 inttostr(trunc(fr*1000000) mod 10)+'Z';
\r
766 procedure beginhightimerrate;
\r
768 {$ifdef mswindows}timebeginperiod(1);{$endif}
\r
771 procedure endhightimerrate;
\r
773 {$ifdef mswindows}timeendperiod(1);{$endif}
\r
778 {$ifdef btimehighrate}beginhightimerrate;{$endif}
\r
779 fillchar(mmtime_driftavg,sizeof(mmtime_driftavg),0);
\r
782 unixtime := unixtimeint;
\r
783 irctime := irctimeint;
\r
786 initialization init;
\r