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
24 colorburst=39375000/11; {3579545.4545....}
\r
29 irctime,unixtime:integer;
\r
31 settimebias:integer;
\r
32 performancecountfreq:extended;
\r
34 function irctimefloat:float;
\r
35 function irctimeint:integer;
\r
37 function unixtimefloat:float;
\r
38 function unixtimeint:integer;
\r
40 function wintimefloat:float;
\r
42 procedure settime(newtime:integer);
\r
43 procedure gettimezone;
\r
44 procedure timehandler;
\r
47 function timestring(i:integer):string;
\r
48 function timestrshort(i:integer):string;
\r
51 function unixtimefloat_systemtime:float;
\r
54 function oletounixfloat(t:float):float;
\r
55 function oletounix(t:tdatetime):integer;
\r
56 function unixtoole(i:float):tdatetime;
\r
59 function mmtimefloat:float;
\r
60 function qpctimefloat:float;
\r
64 procedure gettimeofday(var tv:ttimeval);
\r
69 mmtime_driftavgsize=32;
\r
71 mmtime_warmupcyclelength=15;
\r
73 //this flag is to be set when btime has been running long enough to stabilise
\r
74 warmup_finished:boolean;
\r
76 timefloatbias:float;
\r
78 ticks_freq2:float=0;
\r
79 ticks_freq_known:boolean=false;
\r
80 lastunixtimefloat:float=0;
\r
81 lastsynctime:float=0;
\r
82 lastsyncbias:float=0;
\r
84 mmtime_last:integer=0;
\r
85 mmtime_wrapadd:float;
\r
86 mmtime_lastsyncmm:float=0;
\r
87 mmtime_lastsyncqpc:float=0;
\r
88 mmtime_drift:float=1;
\r
89 mmtime_lastresult:float;
\r
90 mmtime_nextdriftcorrection:float;
\r
91 mmtime_driftavg:array[0..mmtime_driftavgsize] of float;
\r
92 mmtime_synchedqpc:boolean;
\r
94 mmtime_prev_drift:float;
\r
95 mmtime_prev_lastsyncmm:float;
\r
96 mmtime_prev_lastsyncqpc:float;
\r
109 baseunix,unix,unixutil,sockets, {unixutil and sockets needed by unixstuff.inc on some compiler versions}
\r
112 windows,unitsettc,mmsystem,
\r
116 {$include unixstuff.inc}
\r
120 daysdifference=25569;
\r
122 function oletounixfloat(t:float):float;
\r
124 t := (t - daysdifference) * 86400;
\r
128 function oletounix(t:tdatetime):integer;
\r
130 result := trunc(oletounixfloat(t));
\r
133 function unixtoole(i:float):tdatetime;
\r
135 result := ((i)/86400)+daysdifference;
\r
139 highdwordconst=65536.0 * 65536.0;
\r
141 function utrunc(f:float):integer;
\r
142 {converts float to integer, in 32 bits unsigned range}
\r
144 if f >= (highdwordconst/2) then f := f - highdwordconst;
\r
145 result := trunc(f);
\r
148 function uinttofloat(i:integer):float;
\r
149 {converts 32 bits unsigned integer to float}
\r
152 if result < 0 then result := result + highdwordconst;
\r
156 {-----------------------------------------*nix/freepascal code to read time }
\r
158 function unixtimefloat:float;
\r
163 result := tv.tv_sec+(tv.tv_usec/1000000);
\r
166 function wintimefloat:extended;
\r
168 result := unixtimefloat;
\r
171 function unixtimeint:integer;
\r
176 result := tv.tv_sec;
\r
180 {------------------------------ windows/delphi code to read time}
\r
183 {simulate gettimeofday on windows so one can always use gettimeofday if preferred}
\r
185 procedure gettimeofday(var tv:ttimeval);
\r
189 e := unixtimefloat;
\r
190 tv.tv_sec := round(int(e));
\r
191 tv.tv_usec := trunc(frac(e)*1000000);
\r
193 if (tv.tv_usec < 0) then tv.tv_usec := 0;
\r
194 if (tv.tv_usec > 999999) then tv.tv_usec := 999999;
\r
199 time float: gettickcount
\r
200 resolution: 9x: ~55 ms NT: 1/64th of a second
\r
201 guarantees: continuous without any jumps
\r
202 frequency base: same as system clock.
\r
204 note: if called more than once per 49.7 days, 32 bits wrapping is compensated for and it keeps going on.
\r
205 note: i handle the timestamp as signed integer, but with the wrap compensation that works as well, and is faster
\r
208 function mmtimefloat:float;
\r
210 wrapduration=highdwordconst * 0.001;
\r
214 i := gettickcount; {timegettime}
\r
215 if i < mmtime_last then begin
\r
216 mmtime_wrapadd := mmtime_wrapadd + wrapduration;
\r
219 result := mmtime_wrapadd + i * 0.001;
\r
221 if (ticks_freq <> 0) and ticks_freq_known then result := int((result / ticks_freq)+0.5) * ticks_freq; //turn the float into an exact multiple of 1/64th sec to improve accuracy of things using this
\r
224 procedure measure_ticks_freq;
\r
231 if (performancecountfreq = 0) then qpctimefloat;
\r
232 ticks_freq_known := false;
\r
235 repeat g := mmtimefloat until g > f;
\r
238 fillchar(o,sizeof(o),0);
\r
239 o.dwOSVersionInfoSize := sizeof(o);
\r
241 isnt := o.dwPlatformId = VER_PLATFORM_WIN32_NT;
\r
242 { is9x := o.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS;}
\r
245 mmtime_synchedqpc := false;
\r
248 identify mode as: nt64
\r
249 QPC rate: either 3579545 or TSC freq
\r
250 QPC synched to gettickcount: no
\r
251 duration between 2 ticks is constant: yes
\r
252 gettickcount tick duration: 64 Hz
\r
255 identify mode as: nt64
\r
256 QPC rate: TSC freq / 1000
\r
257 QPC synched to gettickcount: no
\r
258 duration between 2 ticks is constant: yes
\r
259 gettickcount tick duration: ~15.6001007 ms, ~64.102 Hz
\r
262 if (f >= 0.014) and (f <= 0.018) and isnt then begin
\r
263 if (performancecountfreq = 3579545) or (performancecountfreq > 50000000) then begin
\r
265 ticks_freq := 1/64;
\r
267 {typical windows 7}
\r
268 ticks_freq := 0.0156001007;
\r
270 ticks_freq_known := true;
\r
271 mmtime_synchedqpc := false;
\r
276 identify mode as: nt100
\r
278 QPC synched to gettickcount: yes
\r
279 duration between 2 ticks is constant: no?
\r
280 gettickcount tick duration: ~99.85 Hz
\r
282 if (performancecountfreq = 1193182) and (f >= 0.008) and (f <= 0.012) and isnt then begin
\r
283 ticks_freq_known := true;
\r
284 ticks_freq2 := 11949 / (colorburst / 3);
\r
285 // ticks_freq2 := 11949 / 1193182;
\r
287 {the ticks freq should be very close to the real one but if it's not exact, it will cause drift and correction jumps}
\r
288 mmtime_synchedqpc := true;
\r
292 if (performancecountfreq = 1193182) and (f >= 0.050) and (f <= 0.060) then begin
\r
293 ticks_freq_known := true;
\r
294 ticks_freq := 65536 / (colorburst / 3);
\r
295 mmtime_synchedqpc := true;
\r
297 ticks_freq_known := true;
\r
298 if ticks_freq <> 0 then ticks_freq2 := ticks_freq;
\r
299 // writeln(formatfloat('0.000000',ticks_freq));
\r
303 time float: QueryPerformanceCounter
\r
305 guarantees: can have forward jumps depending on hardware. can have forward and backwards jitter on dual core.
\r
306 frequency base: on NT, not the system clock, drifts compared to it.
\r
309 function qpctimefloat:extended;
\r
315 p2:tlargeinteger absolute p;
\r
318 if performancecountfreq = 0 then begin
\r
319 QueryPerformancefrequency(p2);
\r
321 if e < 0 then e := e + highdwordconst;
\r
322 performancecountfreq := ((p.highpart*highdwordconst)+e);
\r
324 queryperformancecounter(p2);
\r
326 if e < 0 then e := e + highdwordconst;
\r
328 result := ((p.highpart*highdwordconst)+e)/performancecountfreq;
\r
332 time float: QPC locked to gettickcount
\r
334 guarantees: continuous without any jumps
\r
335 frequency base: same as system clock.
\r
339 function mmqpctimefloat:float;
\r
345 mm,f,qpc,newdrift:float;
\r
348 { retrycount:integer;}
\r
350 if not ticks_freq_known then measure_ticks_freq;
\r
351 { retrycount := maxretries;}
\r
353 qpc := qpctimefloat;
\r
355 f := (qpc - mmtime_lastsyncqpc) * mmtime_drift + mmtime_lastsyncmm;
\r
356 //writeln('XXXX ',formatfloat('0.000000',qpc-mm));
\r
357 qpcjumped := ((f-mm) > ticks_freq2+margin) or ((f-mm) < -margin);
\r
358 // if qpcjumped then writeln('qpc jumped ',(f-mm));
\r
359 if ((qpc > mmtime_nextdriftcorrection) and not mmtime_synchedqpc) or qpcjumped then begin
\r
361 mmtime_nextdriftcorrection := qpc + 1;
\r
363 mmtime_prev_drift := mmtime_drift;
\r
364 mmtime_prev_lastsyncmm := mmtime_lastsyncmm;
\r
365 mmtime_prev_lastsyncqpc := mmtime_lastsyncqpc;
\r
368 { dec(retrycount);}
\r
370 result := qpctimefloat;
\r
373 if f = mm then result := qpctimefloat;
\r
376 qpc := qpctimefloat;
\r
379 if (qpc > result + 0.0001) then begin
\r
384 if (mmtime_lastsyncqpc <> 0) and not qpcjumped then begin
\r
385 newdrift := (mm - mmtime_lastsyncmm) / (qpc - mmtime_lastsyncqpc);
\r
386 mmtime_drift := newdrift;
\r
387 { writeln('raw drift: ',formatfloat('0.00000000',mmtime_drift));}
\r
388 move(mmtime_driftavg[0],mmtime_driftavg[1],sizeof(mmtime_driftavg[0])*high(mmtime_driftavg));
\r
389 mmtime_driftavg[0] := mmtime_drift;
\r
391 { write('averaging drift ',formatfloat('0.00000000',mmtime_drift),' -> ');}
\r
392 { mmtime_drift := 0;}
\r
394 for a := 0 to high(mmtime_driftavg) do begin
\r
395 if mmtime_driftavg[a] <> 0 then inc(b);
\r
396 { mmtime_drift := mmtime_drift + mmtime_driftavg[a];}
\r
398 { mmtime_drift := mmtime_drift / b;}
\r
400 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
401 mmtime_nextdriftcorrection := qpc + a;
\r
402 if (b >= 2) then warmup_finished := true;
\r
403 { writeln(formatfloat('0.00000000',mmtime_drift));}
\r
404 if mmtime_synchedqpc then mmtime_drift := 1;
\r
407 mmtime_lastsyncqpc := qpc;
\r
408 mmtime_lastsyncmm := mm;
\r
409 { writeln(formatfloat('0.00000000',mmtime_drift));}
\r
414 qpc := qpctimefloat;
\r
416 result := (qpc - mmtime_lastsyncqpc) * mmtime_drift + mmtime_lastsyncmm;
\r
418 {f := (qpc - mmtime_prev_lastsyncqpc) * mmtime_prev_drift + mmtime_prev_lastsyncmm;
\r
420 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
427 if (result < mmtime_lastresult) then result := mmtime_lastresult;
\r
428 mmtime_lastresult := result;
\r
431 { free pascals tsystemtime is incomaptible with windows api calls
\r
432 so we declare it ourselves - plugwash
\r
436 TSystemTime = record
\r
444 wMilliseconds: Word;
\r
447 function Date_utc: extended;
\r
449 SystemTime: TSystemTime;
\r
452 GetsystemTime(@SystemTime);
\r
454 GetsystemTime(SystemTime);
\r
456 with SystemTime do Result := EncodeDate(wYear, wMonth, wDay);
\r
459 function Time_utc: extended;
\r
461 SystemTime: TSystemTime;
\r
464 GetsystemTime(@SystemTime);
\r
466 GetsystemTime(SystemTime);
\r
469 Result := EncodeTime(wHour, wMinute, wSecond, wMilliSeconds);
\r
472 function Now_utc: extended;
\r
474 Result := round(Date_utc) + Time_utc;
\r
477 function unixtimefloat_systemtime:float;
\r
479 {result := oletounixfloat(now_utc);}
\r
481 {this method gives exactly the same result with extended precision, but is less sensitive to float rounding in theory}
\r
482 result := oletounixfloat(int(date_utc+0.5))+time_utc*86400;
\r
485 function wintimefloat:extended;
\r
487 result := mmqpctimefloat;
\r
490 function unixtimefloat:float;
\r
496 result := wintimefloat+timefloatbias;
\r
497 f := result-unixtimefloat_systemtime;
\r
498 if ((f > ticks_freq2+margin) or (f < -margin)) or (timefloatbias = 0) then begin
\r
499 // writeln('unixtimefloat init');
\r
500 f := unixtimefloat_systemtime;
\r
502 repeat g := unixtimefloat_systemtime; h := wintimefloat until g > f;
\r
504 timefloatbias := g-h;
\r
505 result := unixtimefloat;
\r
508 {for small changes backwards, guarantee no steps backwards}
\r
509 if (result <= lastunixtimefloat) and (result > lastunixtimefloat-1.5) then result := lastunixtimefloat + 0.0000001;
\r
510 lastunixtimefloat := result;
\r
513 function unixtimeint:integer;
\r
515 result := trunc(unixtimefloat);
\r
519 {-----------------------------------------------end of platform specific}
\r
521 function irctimefloat:float;
\r
523 result := unixtimefloat+settimebias;
\r
526 function irctimeint:integer;
\r
528 result := unixtimeint+settimebias;
\r
532 procedure settime(newtime:integer);
\r
536 a := irctimeint-settimebias;
\r
537 if newtime = 0 then settimebias := 0 else settimebias := newtime-a;
\r
539 irctime := irctimeint;
\r
542 procedure timehandler;
\r
544 if unixtime = 0 then init;
\r
545 unixtime := unixtimeint;
\r
546 irctime := irctimeint;
\r
547 if unixtime and 63 = 0 then begin
\r
548 {update everything, apply timezone changes, clock changes, etc}
\r
550 timefloatbias := 0;
\r
551 unixtime := unixtimeint;
\r
552 irctime := irctimeint;
\r
557 procedure gettimezone;
\r
573 timezone := tzseconds;
\r
576 timezone := (longint(hh) * 3600 + mm * 60 + ss) - (unixtimeint mod 86400);
\r
579 timezone := round((now-now_utc)*86400);
\r
582 while timezone > 43200 do dec(timezone,86400);
\r
583 while timezone < -43200 do inc(timezone,86400);
\r
585 if timezone >= 0 then timezonestr := '+' else timezonestr := '-';
\r
586 l := abs(timezone) div 60;
\r
587 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
590 function timestrshort(i:integer):string;
\r
592 weekday:array[0..6] of string[4]=('Thu','Fri','Sat','Sun','Mon','Tue','Wed');
\r
593 month:array[0..11] of string[4]=('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
\r
595 y,m,d,h,min,sec,ms:word;
\r
598 t := unixtoole(i+timezone);
\r
599 decodedate(t,y,m,d);
\r
600 decodetime(t,h,min,sec,ms);
\r
601 result := weekday[(i+timezone) div 86400 mod 7]+' '+month[m-1]+' '+inttostr(d)+' '+
\r
602 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
606 function timestring(i:integer):string;
\r
608 weekday:array[0..6] of string[10]=('Thursday','Friday','Saturday','Sunday','Monday','Tuesday','Wednesday');
\r
609 month:array[0..11] of string[10]=('January','February','March','April','May','June','July','August','September','October','November','December');
\r
611 y,m,d,h,min,sec,ms:word;
\r
614 t := unixtoole(i+timezone);
\r
615 decodedate(t,y,m,d);
\r
616 decodetime(t,h,min,sec,ms);
\r
617 result := weekday[(i+timezone) div 86400 mod 7]+' '+month[m-1]+' '+inttostr(d)+' '+inttostr(y)+' -- '+
\r
618 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
624 {$ifdef win32}timebeginperiod(1);{$endif} //ensure stable unchanging clock
\r
625 fillchar(mmtime_driftavg,sizeof(mmtime_driftavg),0);
\r
628 unixtime := unixtimeint;
\r
629 irctime := irctimeint;
\r
632 initialization init;
\r