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; // Wednesday August 15 2012 -- 16:21:09 +02:00
\r
54 function timestrshort(i:tunixtimeint):string; // Wed Aug 15 16:21:09 2012
\r
55 function timestriso(i:tunixtimeint):string; // 2012-08-15 16:21:09
\r
56 function timestrisoutc(i:float):string; // 2012-08-15T14:21:09.255553Z
\r
59 function unixtimefloat_systemtime:float;
\r
62 function oletounixfloat(t:float):float;
\r
63 function oletounix(t:tdatetime):tunixtimeint;
\r
64 function unixtoole(i:float):tdatetime;
\r
67 function mmtimefloat:float;
\r
68 function qpctimefloat:float;
\r
72 procedure gettimeofday(var tv:ttimeval);
\r
77 mmtime_driftavgsize=32;
\r
79 mmtime_warmupcyclelength=15;
\r
81 //this flag is to be set when btime has been running long enough to stabilise
\r
82 warmup_finished:boolean;
\r
84 timefloatbias:float;
\r
86 ticks_freq2:float=0;
\r
87 ticks_freq_known:boolean=false;
\r
88 lastunixtimefloat:float=0;
\r
89 lastsynctime:float=0;
\r
90 lastsyncbias:float=0;
\r
92 mmtime_last:integer=0;
\r
93 mmtime_wrapadd:float;
\r
94 mmtime_lastsyncmm:float=0;
\r
95 mmtime_lastsyncqpc:float=0;
\r
96 mmtime_drift:float=1;
\r
97 mmtime_lastresult:float;
\r
98 mmtime_nextdriftcorrection:float;
\r
99 mmtime_driftavg:array[0..mmtime_driftavgsize] of float;
\r
100 mmtime_synchedqpc:boolean;
\r
102 mmtime_prev_drift:float;
\r
103 mmtime_prev_lastsyncmm:float;
\r
104 mmtime_prev_lastsyncqpc:float;
\r
117 baseunix,unix,unixutil,sockets, {unixutil and sockets needed by unixstuff.inc on some compiler versions}
\r
123 windows,unitsettc,mmsystem,
\r
127 {$include unixstuff.inc}
\r
131 daysdifference=25569;
\r
133 function oletounixfloat(t:float):float;
\r
135 t := (t - daysdifference) * 86400;
\r
139 function oletounix(t:tdatetime):tunixtimeint;
\r
141 result := trunc(oletounixfloat(t));
\r
144 function unixtoole(i:float):tdatetime;
\r
146 result := ((i)/86400)+daysdifference;
\r
150 highdwordconst=65536.0 * 65536.0;
\r
152 function utrunc(f:float):integer;
\r
153 {converts float to integer, in 32 bits unsigned range}
\r
155 if f >= (highdwordconst/2) then f := f - highdwordconst;
\r
156 result := trunc(f);
\r
159 function uinttofloat(i:integer):float;
\r
160 {converts 32 bits unsigned integer to float}
\r
163 if result < 0 then result := result + highdwordconst;
\r
167 {-----------------------------------------*nix/freepascal code to read time }
\r
169 function unixtimefloat:float;
\r
174 result := tv.tv_sec+(tv.tv_usec/1000000);
\r
178 {$define monotimefloat_implemented}
\r
180 CLOCK_MONOTONIC = 1;
\r
182 ptimeval = ^ttimeval;
\r
183 tclock_gettime = function(clk_id: integer; tp: ptimeval): integer; cdecl;
\r
186 librt_handle:pointer;
\r
187 librt_inited:boolean;
\r
188 clock_gettime: tclock_gettime;
\r
190 function monotimefloat:float;
\r
194 if not librt_inited then begin
\r
195 librt_inited := true;
\r
196 clock_gettime := nil;
\r
197 librt_handle := dlopen('librt.so', RTLD_LAZY);
\r
198 if assigned(librt_handle) then begin
\r
199 clock_gettime := dlsym(librt_handle, 'clock_gettime');
\r
202 if assigned(clock_gettime) then begin
\r
203 if clock_gettime(CLOCK_MONOTONIC, @ts) = 0 then begin
\r
204 //note this really returns nanoseconds
\r
205 result := ts.tv_sec + ts.tv_usec / 1000000000.0;
\r
210 result := unixtimefloat;
\r
216 {$ifdef darwin} {mac OS X}
\r
217 {$define monotimefloat_implemented}
\r
220 tmach_timebase_info = packed record
\r
224 pmach_timebase_info = ^tmach_timebase_info;
\r
226 function mach_absolute_time: int64; cdecl; external;
\r
227 function mach_timebase_info(info: pmach_timebase_info): integer; cdecl; external;
\r
230 timebase_info: tmach_timebase_info;
\r
232 function monotimefloat:float;
\r
236 if timebase_info.denom = 0 then begin
\r
237 mach_timebase_info(@timebase_info);
\r
239 i := mach_absolute_time;
\r
240 result := (i * timebase_info.numer div timebase_info.denom) / 1000000000.0;
\r
243 {$endif} {darwin, mac OS X}
\r
246 {$ifndef monotimefloat_implemented} {fallback}
\r
248 function monotimefloat:extended;
\r
250 result := unixtimefloat;
\r
253 {$endif} {monotimefloat fallback}
\r
256 function unixtimeint:tunixtimeint;
\r
261 result := tv.tv_sec;
\r
264 {------------------------------ end of *nix/freepascal section}
\r
267 {------------------------------ windows/delphi code to read time}
\r
270 {simulate gettimeofday on windows so one can always use gettimeofday if preferred}
\r
272 procedure gettimeofday(var tv:ttimeval);
\r
276 e := unixtimefloat;
\r
277 tv.tv_sec := round(int(e));
\r
278 tv.tv_usec := trunc(frac(e)*1000000);
\r
280 if (tv.tv_usec < 0) then tv.tv_usec := 0;
\r
281 if (tv.tv_usec > 999999) then tv.tv_usec := 999999;
\r
286 time float: gettickcount
\r
287 resolution: 9x: ~55 ms NT: 1/64th of a second
\r
288 guarantees: continuous without any jumps
\r
289 frequency base: same as system clock.
\r
291 note: if called more than once per 49.7 days, 32 bits wrapping is compensated for and it keeps going on.
\r
292 note: i handle the timestamp as signed integer, but with the wrap compensation that works as well, and is faster
\r
295 function mmtimefloat:float;
\r
297 wrapduration=highdwordconst * 0.001;
\r
302 i := gettickcount; {timegettime}
\r
303 if i < mmtime_last then begin
\r
304 mmtime_wrapadd := mmtime_wrapadd + wrapduration;
\r
307 result := mmtime_wrapadd + i * 0.001;
\r
309 if (ticks_freq <> 0) and ticks_freq_known then begin
\r
310 {the value we get is rounded to 1 ms, but the ticks are not a multiple of 1 ms
\r
311 this makes the value noisy. use the known ticks frequency to restore the original value}
\r
312 temp := int((result / ticks_freq)+0.5) * ticks_freq;
\r
314 {if the known ticks freq is wrong (can happen), disable the un-rounding behavior
\r
315 this will be a bit less accurate but it prevents problems}
\r
316 if abs(temp - result) > 0.002 then begin
\r
318 end else result := temp;
\r
322 procedure measure_ticks_freq;
\r
328 adjust1,adjust2:cardinal;
\r
329 adjustbool:longbool;
\r
331 if (performancecountfreq = 0) then qpctimefloat;
\r
332 ticks_freq_known := false;
\r
335 repeat g := mmtimefloat until g > f;
\r
338 fillchar(o,sizeof(o),0);
\r
339 o.dwOSVersionInfoSize := sizeof(o);
\r
341 isnt := o.dwPlatformId = VER_PLATFORM_WIN32_NT;
\r
342 { is9x := o.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS;}
\r
345 mmtime_synchedqpc := false;
\r
347 if (isnt and (o.dwMajorVersion >= 5)) then begin
\r
348 {windows 2000 and later: query tick rate from OS in 100 ns units
\r
349 typical rates: XP: 156250 or 100144, windows 7: 156001}
\r
350 if GetSystemTimeAdjustment(adjust1,adjust2,adjustbool) then begin
\r
351 ticks_freq := adjust1 / 10000000.0;
\r
352 ticks_freq_known := true;
\r
353 mmtime_synchedqpc := false;
\r
358 if (performancecountfreq = 1193182) and (f >= 0.050) and (f <= 0.060) then begin
\r
359 ticks_freq_known := true;
\r
360 ticks_freq := 65536 / (colorburst / 3);
\r
361 mmtime_synchedqpc := true;
\r
363 ticks_freq_known := true;
\r
364 if ticks_freq <> 0 then ticks_freq2 := ticks_freq;
\r
365 // writeln(formatfloat('0.000000',ticks_freq));
\r
369 time float: QueryPerformanceCounter
\r
371 guarantees: can have forward jumps depending on hardware. can have forward and backwards jitter on dual core.
\r
372 frequency base: on NT, not the system clock, drifts compared to it.
\r
375 function qpctimefloat:extended;
\r
381 p2:tlargeinteger absolute p;
\r
384 if performancecountfreq = 0 then begin
\r
385 QueryPerformancefrequency(p2);
\r
387 if e < 0 then e := e + highdwordconst;
\r
388 performancecountfreq := ((p.highpart*highdwordconst)+e);
\r
390 queryperformancecounter(p2);
\r
392 if e < 0 then e := e + highdwordconst;
\r
394 result := ((p.highpart*highdwordconst)+e)/performancecountfreq;
\r
398 time float: QPC locked to gettickcount
\r
400 guarantees: continuous without any jumps
\r
401 frequency base: same as system clock.
\r
405 function mmqpctimefloat:float;
\r
411 mm,f,qpc,newdrift:float;
\r
414 { retrycount:integer;}
\r
416 if not ticks_freq_known then measure_ticks_freq;
\r
417 { retrycount := maxretries;}
\r
419 qpc := qpctimefloat;
\r
421 f := (qpc - mmtime_lastsyncqpc) * mmtime_drift + mmtime_lastsyncmm;
\r
422 //writeln('XXXX ',formatfloat('0.000000',qpc-mm));
\r
423 qpcjumped := ((f-mm) > ticks_freq2+margin) or ((f-mm) < -margin);
\r
424 // if qpcjumped then writeln('qpc jumped ',(f-mm));
\r
425 if ((qpc > mmtime_nextdriftcorrection) and not mmtime_synchedqpc) or qpcjumped then begin
\r
427 mmtime_nextdriftcorrection := qpc + 1;
\r
429 mmtime_prev_drift := mmtime_drift;
\r
430 mmtime_prev_lastsyncmm := mmtime_lastsyncmm;
\r
431 mmtime_prev_lastsyncqpc := mmtime_lastsyncqpc;
\r
434 { dec(retrycount);}
\r
436 result := qpctimefloat;
\r
439 if f = mm then result := qpctimefloat;
\r
442 qpc := qpctimefloat;
\r
445 if (qpc > result + 0.0001) then begin
\r
450 if (mmtime_lastsyncqpc <> 0) and not qpcjumped then begin
\r
451 newdrift := (mm - mmtime_lastsyncmm) / (qpc - mmtime_lastsyncqpc);
\r
452 mmtime_drift := newdrift;
\r
453 { writeln('raw drift: ',formatfloat('0.00000000',mmtime_drift));}
\r
454 move(mmtime_driftavg[0],mmtime_driftavg[1],sizeof(mmtime_driftavg[0])*high(mmtime_driftavg));
\r
455 mmtime_driftavg[0] := mmtime_drift;
\r
457 { write('averaging drift ',formatfloat('0.00000000',mmtime_drift),' -> ');}
\r
458 { mmtime_drift := 0;}
\r
460 for a := 0 to high(mmtime_driftavg) do begin
\r
461 if mmtime_driftavg[a] <> 0 then inc(b);
\r
462 { mmtime_drift := mmtime_drift + mmtime_driftavg[a];}
\r
464 { mmtime_drift := mmtime_drift / b;}
\r
466 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
467 mmtime_nextdriftcorrection := qpc + a;
\r
468 if (b >= 2) then warmup_finished := true;
\r
469 { writeln(formatfloat('0.00000000',mmtime_drift));}
\r
470 if mmtime_synchedqpc then mmtime_drift := 1;
\r
473 mmtime_lastsyncqpc := qpc;
\r
474 mmtime_lastsyncmm := mm;
\r
475 { writeln(formatfloat('0.00000000',mmtime_drift));}
\r
480 qpc := qpctimefloat;
\r
482 result := (qpc - mmtime_lastsyncqpc) * mmtime_drift + mmtime_lastsyncmm;
\r
484 {f := (qpc - mmtime_prev_lastsyncqpc) * mmtime_prev_drift + mmtime_prev_lastsyncmm;
\r
486 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
493 if (result < mmtime_lastresult) then result := mmtime_lastresult;
\r
494 mmtime_lastresult := result;
\r
497 { free pascals tsystemtime is incomaptible with windows api calls
\r
498 so we declare it ourselves - plugwash
\r
502 TSystemTime = record
\r
510 wMilliseconds: Word;
\r
513 function Date_utc: extended;
\r
515 SystemTime: TSystemTime;
\r
518 GetsystemTime(@SystemTime);
\r
520 GetsystemTime(SystemTime);
\r
522 with SystemTime do Result := EncodeDate(wYear, wMonth, wDay);
\r
525 function Time_utc: extended;
\r
527 SystemTime: TSystemTime;
\r
530 GetsystemTime(@SystemTime);
\r
532 GetsystemTime(SystemTime);
\r
535 Result := EncodeTime(wHour, wMinute, wSecond, wMilliSeconds);
\r
538 function Now_utc: extended;
\r
540 Result := round(Date_utc) + Time_utc;
\r
543 function unixtimefloat_systemtime:float;
\r
545 {result := oletounixfloat(now_utc);}
\r
547 {this method gives exactly the same result with extended precision, but is less sensitive to float rounding in theory}
\r
548 result := oletounixfloat(int(date_utc+0.5))+time_utc*86400;
\r
551 function monotimefloat:extended;
\r
553 result := mmqpctimefloat;
\r
556 function unixtimefloat:float;
\r
562 result := monotimefloat+timefloatbias;
\r
563 f := result-unixtimefloat_systemtime;
\r
564 if ((f > ticks_freq2+margin) or (f < -margin)) or (timefloatbias = 0) then begin
\r
565 // writeln('unixtimefloat init');
\r
566 f := unixtimefloat_systemtime;
\r
568 repeat g := unixtimefloat_systemtime; h := monotimefloat until g > f;
\r
570 timefloatbias := g-h;
\r
571 result := unixtimefloat;
\r
574 {for small changes backwards, guarantee no steps backwards}
\r
575 if (result <= lastunixtimefloat) and (result > lastunixtimefloat-1.5) then result := lastunixtimefloat + 0.0000001;
\r
576 lastunixtimefloat := result;
\r
579 function unixtimeint:tunixtimeint;
\r
581 result := trunc(unixtimefloat);
\r
585 {-----------------------------------------------end of platform specific}
\r
587 function wintimefloat:float;
\r
589 result := monotimefloat;
\r
592 function irctimefloat:float;
\r
594 result := unixtimefloat+settimebias;
\r
597 function irctimeint:tunixtimeint;
\r
599 result := unixtimeint+settimebias;
\r
603 procedure settime(newtime:tunixtimeint);
\r
607 a := irctimeint-settimebias;
\r
608 if newtime = 0 then settimebias := 0 else settimebias := newtime-a;
\r
610 irctime := irctimeint;
\r
613 procedure timehandler;
\r
615 if unixtime = 0 then init;
\r
616 unixtime := unixtimeint;
\r
617 irctime := irctimeint;
\r
618 if unixtime and 63 = 0 then begin
\r
619 {update everything, apply timezone changes, clock changes, etc}
\r
621 timefloatbias := 0;
\r
622 unixtime := unixtimeint;
\r
623 irctime := irctimeint;
\r
628 procedure gettimezone;
\r
644 timezone := tzseconds;
\r
647 timezone := (longint(hh) * 3600 + mm * 60 + ss) - (unixtimeint mod 86400);
\r
650 timezone := round((now-now_utc)*86400);
\r
653 while timezone > 43200 do dec(timezone,86400);
\r
654 while timezone < -43200 do inc(timezone,86400);
\r
656 if timezone >= 0 then timezonestr := '+' else timezonestr := '-';
\r
657 l := abs(timezone) div 60;
\r
658 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
661 function timestrshort(i:tunixtimeint):string;
\r
663 weekday:array[0..6] of string[4]=('Thu','Fri','Sat','Sun','Mon','Tue','Wed');
\r
664 month:array[0..11] of string[4]=('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
\r
666 y,m,d,h,min,sec,ms:word;
\r
669 t := unixtoole(i+timezone);
\r
670 decodedate(t,y,m,d);
\r
671 decodetime(t,h,min,sec,ms);
\r
672 result := weekday[(i+timezone) div 86400 mod 7]+' '+month[m-1]+' '+inttostr(d)+' '+
\r
673 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
677 function timestring(i:tunixtimeint):string;
\r
679 weekday:array[0..6] of string[10]=('Thursday','Friday','Saturday','Sunday','Monday','Tuesday','Wednesday');
\r
680 month:array[0..11] of string[10]=('January','February','March','April','May','June','July','August','September','October','November','December');
\r
682 y,m,d,h,min,sec,ms:word;
\r
685 t := unixtoole(i+timezone);
\r
686 decodedate(t,y,m,d);
\r
687 decodetime(t,h,min,sec,ms);
\r
688 result := weekday[(i+timezone) div 86400 mod 7]+' '+month[m-1]+' '+inttostr(d)+' '+inttostr(y)+' -- '+
\r
689 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 function timestriso(i:tunixtimeint):string;
\r
695 y,m,d,h,min,sec,ms:word;
\r
698 t := unixtoole(i+timezone);
\r
699 decodedate(t,y,m,d);
\r
700 decodetime(t,h,min,sec,ms);
\r
701 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
704 function timestrisoutc(i:float):string;
\r
706 y,m,d,h,min,sec,ms:word;
\r
711 decodedate(t,y,m,d);
\r
712 decodetime(t,h,min,sec,ms);
\r
713 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
716 result := result + '.'+
\r
717 inttostr(trunc(fr*10) mod 10)+
\r
718 inttostr(trunc(fr*100) mod 10)+
\r
719 inttostr(trunc(fr*1000) mod 10)+
\r
720 inttostr(trunc(fr*10000) mod 10)+
\r
721 inttostr(trunc(fr*100000) mod 10)+
\r
722 inttostr(trunc(fr*1000000) mod 10)+'Z';
\r
729 {$ifdef mswindows}timebeginperiod(1);{$endif} //ensure stable unchanging clock
\r
730 fillchar(mmtime_driftavg,sizeof(mmtime_driftavg),0);
\r
733 unixtime := unixtimeint;
\r
734 irctime := irctimeint;
\r
737 initialization init;
\r