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
181 result := tv.tv_sec+(tv.tv_usec/1000000);
\r
185 {$define monotimefloat_implemented}
\r
187 CLOCK_MONOTONIC = 1;
\r
189 ptimeval = ^ttimeval;
\r
190 tclock_gettime = function(clk_id: integer; tp: ptimeval): integer; cdecl;
\r
193 librt_handle:pointer;
\r
194 librt_inited:boolean;
\r
195 clock_gettime: tclock_gettime;
\r
197 function monotimefloat:float;
\r
201 if not librt_inited then begin
\r
202 librt_inited := true;
\r
203 clock_gettime := nil;
\r
204 librt_handle := dlopen('librt.so', RTLD_LAZY);
\r
205 if assigned(librt_handle) then begin
\r
206 clock_gettime := dlsym(librt_handle, 'clock_gettime');
\r
209 if assigned(clock_gettime) then begin
\r
210 if clock_gettime(CLOCK_MONOTONIC, @ts) = 0 then begin
\r
211 //note this really returns nanoseconds
\r
212 result := ts.tv_sec + ts.tv_usec / 1000000000.0;
\r
217 result := unixtimefloat;
\r
223 {$ifdef darwin} {mac OS X}
\r
224 {$define monotimefloat_implemented}
\r
227 tmach_timebase_info = packed record
\r
231 pmach_timebase_info = ^tmach_timebase_info;
\r
233 function mach_absolute_time: int64; cdecl; external;
\r
234 function mach_timebase_info(info: pmach_timebase_info): integer; cdecl; external;
\r
237 timebase_info: tmach_timebase_info;
\r
239 function monotimefloat:float;
\r
243 if timebase_info.denom = 0 then begin
\r
244 mach_timebase_info(@timebase_info);
\r
246 i := mach_absolute_time;
\r
247 result := (i * timebase_info.numer div timebase_info.denom) / 1000000000.0;
\r
250 {$endif} {darwin, mac OS X}
\r
253 {$ifndef monotimefloat_implemented} {fallback}
\r
255 function monotimefloat:extended;
\r
257 result := unixtimefloat;
\r
260 {$endif} {monotimefloat fallback}
\r
263 function unixtimeint:tunixtimeint;
\r
268 result := tv.tv_sec;
\r
271 {------------------------------ end of *nix/freepascal section}
\r
274 {------------------------------ windows/delphi code to read time}
\r
277 {simulate gettimeofday on windows so one can always use gettimeofday if preferred}
\r
279 procedure gettimeofday(var tv:ttimeval);
\r
283 e := unixtimefloat;
\r
284 tv.tv_sec := round(int(e));
\r
285 tv.tv_usec := trunc(frac(e)*1000000);
\r
287 if (tv.tv_usec < 0) then tv.tv_usec := 0;
\r
288 if (tv.tv_usec > 999999) then tv.tv_usec := 999999;
\r
293 time float: gettickcount
\r
294 resolution: 9x: ~55 ms NT: 1/64th of a second
\r
295 guarantees: continuous without any jumps
\r
296 frequency base: same as system clock.
\r
298 note: if called more than once per 49.7 days, 32 bits wrapping is compensated for and it keeps going on.
\r
299 note: i handle the timestamp as signed integer, but with the wrap compensation that works as well, and is faster
\r
302 function mmtimefloat:float;
\r
304 wrapduration=highdwordconst * 0.001;
\r
309 i := gettickcount; {timegettime}
\r
310 if i < mmtime_last then begin
\r
311 mmtime_wrapadd := mmtime_wrapadd + wrapduration;
\r
314 result := mmtime_wrapadd + i * 0.001;
\r
316 if (ticks_freq <> 0) and ticks_freq_known then begin
\r
317 {the value we get is rounded to 1 ms, but the ticks are not a multiple of 1 ms
\r
318 this makes the value noisy. use the known ticks frequency to restore the original value}
\r
319 temp := int((result / ticks_freq)+0.5) * ticks_freq;
\r
321 {if the known ticks freq is wrong (can happen), disable the un-rounding behavior
\r
322 this will be a bit less accurate but it prevents problems}
\r
323 if abs(temp - result) > 0.002 then begin
\r
325 end else result := temp;
\r
329 procedure measure_ticks_freq;
\r
335 adjust1,adjust2:cardinal;
\r
336 adjustbool:longbool;
\r
338 if (performancecountfreq = 0) then qpctimefloat;
\r
339 ticks_freq_known := false;
\r
342 repeat g := mmtimefloat until g > f;
\r
345 fillchar(o,sizeof(o),0);
\r
346 o.dwOSVersionInfoSize := sizeof(o);
\r
348 isnt := o.dwPlatformId = VER_PLATFORM_WIN32_NT;
\r
349 { is9x := o.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS;}
\r
352 mmtime_synchedqpc := false;
\r
354 if (isnt and (o.dwMajorVersion >= 5)) then begin
\r
355 {windows 2000 and later: query tick rate from OS in 100 ns units
\r
356 typical rates: XP: 156250 or 100144, windows 7: 156001}
\r
357 if GetSystemTimeAdjustment(adjust1,adjust2,adjustbool) then begin
\r
358 ticks_freq := adjust1 / 10000000.0;
\r
359 ticks_freq_known := true;
\r
360 mmtime_synchedqpc := false;
\r
365 if (performancecountfreq = 1193182) and (f >= 0.050) and (f <= 0.060) then begin
\r
366 ticks_freq_known := true;
\r
367 ticks_freq := 65536 / (colorburst / 3);
\r
368 mmtime_synchedqpc := true;
\r
370 ticks_freq_known := true;
\r
371 if ticks_freq <> 0 then ticks_freq2 := ticks_freq;
\r
372 // writeln(formatfloat('0.000000',ticks_freq));
\r
376 time float: QueryPerformanceCounter
\r
378 guarantees: can have forward jumps depending on hardware. can have forward and backwards jitter on dual core.
\r
379 frequency base: on NT, not the system clock, drifts compared to it.
\r
382 function qpctimefloat:extended;
\r
388 p2:tlargeinteger absolute p;
\r
391 if performancecountfreq = 0 then begin
\r
392 QueryPerformancefrequency(p2);
\r
394 if e < 0 then e := e + highdwordconst;
\r
395 performancecountfreq := ((p.highpart*highdwordconst)+e);
\r
397 queryperformancecounter(p2);
\r
399 if e < 0 then e := e + highdwordconst;
\r
401 result := ((p.highpart*highdwordconst)+e)/performancecountfreq;
\r
405 time float: QPC locked to gettickcount
\r
407 guarantees: continuous without any jumps
\r
408 frequency base: same as system clock.
\r
412 function mmqpctimefloat:float;
\r
418 mm,f,qpc,newdrift:float;
\r
421 { retrycount:integer;}
\r
423 if not ticks_freq_known then measure_ticks_freq;
\r
424 { retrycount := maxretries;}
\r
426 qpc := qpctimefloat;
\r
428 f := (qpc - mmtime_lastsyncqpc) * mmtime_drift + mmtime_lastsyncmm;
\r
429 //writeln('XXXX ',formatfloat('0.000000',qpc-mm));
\r
430 qpcjumped := ((f-mm) > ticks_freq2+margin) or ((f-mm) < -margin);
\r
431 // if qpcjumped then writeln('qpc jumped ',(f-mm));
\r
432 if ((qpc > mmtime_nextdriftcorrection) and not mmtime_synchedqpc) or qpcjumped then begin
\r
434 mmtime_nextdriftcorrection := qpc + 1;
\r
436 mmtime_prev_drift := mmtime_drift;
\r
437 mmtime_prev_lastsyncmm := mmtime_lastsyncmm;
\r
438 mmtime_prev_lastsyncqpc := mmtime_lastsyncqpc;
\r
441 { dec(retrycount);}
\r
443 result := qpctimefloat;
\r
446 if f = mm then result := qpctimefloat;
\r
449 qpc := qpctimefloat;
\r
452 if (qpc > result + 0.0001) then begin
\r
457 if (mmtime_lastsyncqpc <> 0) and not qpcjumped then begin
\r
458 newdrift := (mm - mmtime_lastsyncmm) / (qpc - mmtime_lastsyncqpc);
\r
459 mmtime_drift := newdrift;
\r
460 { writeln('raw drift: ',formatfloat('0.00000000',mmtime_drift));}
\r
461 move(mmtime_driftavg[0],mmtime_driftavg[1],sizeof(mmtime_driftavg[0])*high(mmtime_driftavg));
\r
462 mmtime_driftavg[0] := mmtime_drift;
\r
464 { write('averaging drift ',formatfloat('0.00000000',mmtime_drift),' -> ');}
\r
465 { mmtime_drift := 0;}
\r
467 for a := 0 to high(mmtime_driftavg) do begin
\r
468 if mmtime_driftavg[a] <> 0 then inc(b);
\r
469 { mmtime_drift := mmtime_drift + mmtime_driftavg[a];}
\r
471 { mmtime_drift := mmtime_drift / b;}
\r
473 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
474 mmtime_nextdriftcorrection := qpc + a;
\r
475 if (b >= 2) then warmup_finished := true;
\r
476 { writeln(formatfloat('0.00000000',mmtime_drift));}
\r
477 if mmtime_synchedqpc then mmtime_drift := 1;
\r
480 mmtime_lastsyncqpc := qpc;
\r
481 mmtime_lastsyncmm := mm;
\r
482 { writeln(formatfloat('0.00000000',mmtime_drift));}
\r
487 qpc := qpctimefloat;
\r
489 result := (qpc - mmtime_lastsyncqpc) * mmtime_drift + mmtime_lastsyncmm;
\r
491 {f := (qpc - mmtime_prev_lastsyncqpc) * mmtime_prev_drift + mmtime_prev_lastsyncmm;
\r
493 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
500 if (result < mmtime_lastresult) then result := mmtime_lastresult;
\r
501 mmtime_lastresult := result;
\r
504 { free pascals tsystemtime is incompatible with windows api calls
\r
505 so we declare it ourselves - plugwash
\r
509 TSystemTime = record
\r
517 wMilliseconds: Word;
\r
520 function Date_utc: extended;
\r
522 SystemTime: TSystemTime;
\r
525 GetsystemTime(@SystemTime);
\r
527 GetsystemTime(SystemTime);
\r
529 with SystemTime do Result := EncodeDate(wYear, wMonth, wDay);
\r
532 function Time_utc: extended;
\r
534 SystemTime: TSystemTime;
\r
537 GetsystemTime(@SystemTime);
\r
539 GetsystemTime(SystemTime);
\r
542 Result := EncodeTime(wHour, wMinute, wSecond, wMilliSeconds);
\r
545 function Now_utc: extended;
\r
547 Result := round(Date_utc) + Time_utc;
\r
550 function unixtimefloat_systemtime:float;
\r
552 {result := oletounixfloat(now_utc);}
\r
554 {this method gives exactly the same result with extended precision, but is less sensitive to float rounding in theory}
\r
555 result := oletounixfloat(int(date_utc+0.5))+time_utc*86400;
\r
558 function monotimefloat:extended;
\r
560 result := mmqpctimefloat;
\r
566 GetSystemTimePreciseAsFileTime:procedure(var v:tfiletime); stdcall;
\r
567 win8inited:boolean;
\r
569 procedure initwin8;
\r
574 win8inited := true;
\r
575 dllhandle := loadlibrary('kernel32.dll');
\r
576 if (dllhandle <> 0) then begin
\r
577 GetSystemTimePreciseAsFileTime := getprocaddress(dllhandle,'GetSystemTimePreciseAsFileTime');
\r
582 function unixtimefloat_win8:float;
\r
585 i:int64 absolute ft;
\r
587 GetSystemTimePreciseAsFileTime(ft);
\r
588 {change from windows 1601-01-01 to unix 1970-01-01.
\r
589 use integer math for this, to preserve precision}
\r
590 dec(i, 116444736000000000);
\r
591 result := (i / 10000000);
\r
596 function unixtimefloat:float;
\r
602 if not btimenowin8 then begin
\r
603 if not win8inited then initwin8;
\r
604 if assigned(@GetSystemTimePreciseAsFileTime) then begin
\r
605 result := unixtimefloat_win8;
\r
610 result := monotimefloat+timefloatbias;
\r
611 f := result-unixtimefloat_systemtime;
\r
612 if ((f > ticks_freq2+margin) or (f < -margin)) or (timefloatbias = 0) then begin
\r
613 // writeln('unixtimefloat init');
\r
614 f := unixtimefloat_systemtime;
\r
616 repeat g := unixtimefloat_systemtime; h := monotimefloat until g > f;
\r
618 timefloatbias := g-h;
\r
619 result := unixtimefloat;
\r
622 {for small changes backwards, guarantee no steps backwards}
\r
623 if (result <= lastunixtimefloat) and (result > lastunixtimefloat-1.5) then result := lastunixtimefloat + 0.0000001;
\r
624 lastunixtimefloat := result;
\r
627 function unixtimeint:tunixtimeint;
\r
629 result := trunc(unixtimefloat);
\r
633 {-----------------------------------------------end of platform specific}
\r
635 function wintimefloat:float;
\r
637 result := monotimefloat;
\r
640 function irctimefloat:float;
\r
642 result := unixtimefloat+settimebias;
\r
645 function irctimeint:tunixtimeint;
\r
647 result := unixtimeint+settimebias;
\r
651 procedure settime(newtime:tunixtimeint);
\r
655 a := irctimeint-settimebias;
\r
656 if newtime = 0 then settimebias := 0 else settimebias := newtime-a;
\r
658 irctime := irctimeint;
\r
661 procedure timehandler;
\r
663 if unixtime = 0 then init;
\r
664 unixtime := unixtimeint;
\r
665 irctime := irctimeint;
\r
666 if unixtime and 63 = 0 then begin
\r
667 {update everything, apply timezone changes, clock changes, etc}
\r
669 timefloatbias := 0;
\r
670 unixtime := unixtimeint;
\r
671 irctime := irctimeint;
\r
676 procedure gettimezone;
\r
692 timezone := tzseconds;
\r
695 timezone := (longint(hh) * 3600 + mm * 60 + ss) - (unixtimeint mod 86400);
\r
698 timezone := round((now-now_utc)*86400);
\r
701 while timezone > 43200 do dec(timezone,86400);
\r
702 while timezone < -43200 do inc(timezone,86400);
\r
704 if timezone >= 0 then timezonestr := '+' else timezonestr := '-';
\r
705 l := abs(timezone) div 60;
\r
706 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
709 function timestrshort(i:tunixtimeint):string;
\r
711 weekday:array[0..6] of string[4]=('Thu','Fri','Sat','Sun','Mon','Tue','Wed');
\r
712 month:array[0..11] of string[4]=('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
\r
714 y,m,d,h,min,sec,ms:word;
\r
717 t := unixtoole(i+timezone);
\r
718 decodedate(t,y,m,d);
\r
719 decodetime(t,h,min,sec,ms);
\r
720 result := weekday[(i+timezone) div 86400 mod 7]+' '+month[m-1]+' '+inttostr(d)+' '+
\r
721 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
725 function timestring(i:tunixtimeint):string;
\r
727 weekday:array[0..6] of string[10]=('Thursday','Friday','Saturday','Sunday','Monday','Tuesday','Wednesday');
\r
728 month:array[0..11] of string[10]=('January','February','March','April','May','June','July','August','September','October','November','December');
\r
730 y,m,d,h,min,sec,ms:word;
\r
733 t := unixtoole(i+timezone);
\r
734 decodedate(t,y,m,d);
\r
735 decodetime(t,h,min,sec,ms);
\r
736 result := weekday[(i+timezone) div 86400 mod 7]+' '+month[m-1]+' '+inttostr(d)+' '+inttostr(y)+' -- '+
\r
737 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
741 function timestriso(i:tunixtimeint):string;
\r
743 y,m,d,h,min,sec,ms:word;
\r
746 t := unixtoole(i+timezone);
\r
747 decodedate(t,y,m,d);
\r
748 decodetime(t,h,min,sec,ms);
\r
749 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
752 function timestrisoutc(i:float):string;
\r
754 y,m,d,h,min,sec,ms:word;
\r
759 decodedate(t,y,m,d);
\r
760 decodetime(t,h,min,sec,ms);
\r
761 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
764 result := result + '.'+
\r
765 inttostr(trunc(fr*10) mod 10)+
\r
766 inttostr(trunc(fr*100) mod 10)+
\r
767 inttostr(trunc(fr*1000) mod 10)+
\r
768 inttostr(trunc(fr*10000) mod 10)+
\r
769 inttostr(trunc(fr*100000) mod 10)+
\r
770 inttostr(trunc(fr*1000000) mod 10)+'Z';
\r
774 procedure beginhightimerrate;
\r
776 {$ifdef mswindows}timebeginperiod(1);{$endif}
\r
779 procedure endhightimerrate;
\r
781 {$ifdef mswindows}timeendperiod(1);{$endif}
\r
786 {$ifdef btimehighrate}beginhightimerrate;{$endif}
\r
787 fillchar(mmtime_driftavg,sizeof(mmtime_driftavg),0);
\r
790 unixtime := unixtimeint;
\r
791 irctime := irctimeint;
\r
794 initialization init;
\r