From 1eee6366bbaa10a34232046fee3aa83181bc452f Mon Sep 17 00:00:00 2001 From: beware Date: Sun, 5 Oct 2025 20:40:45 +0000 Subject: [PATCH] btime overhaul. newer APIs. added btime_gettime. now requires int64. --- btime.pas | 814 +++++++++++++++++++++++++++++++++------------- ltimevalstuff.pas | 12 +- unixstuff.inc | 4 +- 3 files changed, 602 insertions(+), 228 deletions(-) diff --git a/btime.pas b/btime.pas index 4052493..6ee3dbb 100644 --- a/btime.pas +++ b/btime.pas @@ -3,8 +3,28 @@ which is included in the package ----------------------------------------------------------------------------- } { -this unit returns unix timestamp with seconds and microseconds (as float) -works on windows/delphi, and on freepascal on unix. +this unit has several functions for getting unix and monotonic time and UTC offset on both windows and linux/unix + +this unit aims to work on delphi 6 and later, both x86 and x64, on win95 and later +delphi 5 may work (untested). +as well as freepascal on linux x86 and x64 and freebsd x64 (tested), windows, and other unixes (untested) + +provided functions. all are available on both windows and linux/unix: +- unix timestamp as a (double or extended) float or integer: unixtimefloat, unixtimeint +- monotonic timestamp as float: monotimefloat, wintimefloat (both are equivalent) +- _coarse versions of the floats, which can be faster, and precision in the milliseconds. +- btime_gettime: a unified function like clock_gettime. less reliant on floats. +- tzgetoffset returns the UTC offset (timezone) in seconds + +- on windows, it provides the legacy function gettimeofday (on unix, use the one provided by the OS units) + +other things in the interface are often more implementation specific, there for legacy reasons, and not guaranteed stable + +this unit should be 2038 safe: +- seconds are handled as 64 bits +- on 32 bits linux, it uses clock_gettime64 if available +- for getting the UTC offset on unix, this unit does its own, 64 bits aware, parsing of the zoneinfo file +- tested with clock set after 2038 } @@ -20,22 +40,92 @@ interface {$ifdef mswindows} uses ltimevalstuff; -{$endif} +{$endif} + +{$ifdef linux} +uses + linux,syscall; +{$endif} + +{$ifdef freebsd} +uses + freebsd; +{$endif} + +{$ifdef FPC_HAS_TYPE_EXTENDED}{$define has_extended}{$endif} +{$ifndef fpc}{$ifdef cpu386}{$define has_extended}{$endif}{$endif} type + {$ifdef has_extended} float=extended; - tunixtimeint={$ifdef ver100}longint;{$else}int64;{$endif} + {$else} + float=double; + {$endif} + tunixtimeint=int64; const colorburst=39375000/11; {3579545.4545....} + { + CLOCK_MONOTONIC is the standard monotonic time offered by the OS, it may or may not include suspend time + CLOCK_BOOTTIME includes suspend time. + CLOCK_UPTIME excludes suspend time. + } + + {$ifdef mswindows} + CLOCK_REALTIME=0; + CLOCK_MONOTONIC=1; + CLOCK_REALTIME_COARSE=2; + CLOCK_MONOTONIC_COARSE=3; + CLOCK_BOOTTIME=CLOCK_MONOTONIC; //GetTickCount + CLOCK_UPTIME=4; //QueryUnbiasedInterruptTime, fallback to QueryPerformanceCounter + CLOCK_UPTIME_FAST=CLOCK_UPTIME; + {$endif} + + {$ifdef linux} + CLOCK_REALTIME=linux.CLOCK_REALTIME; + CLOCK_MONOTONIC=linux.CLOCK_MONOTONIC; + CLOCK_REALTIME_COARSE=linux.CLOCK_REALTIME_COARSE; + CLOCK_MONOTONIC_COARSE=linux.CLOCK_MONOTONIC_COARSE; + CLOCK_BOOTTIME=7; //linux.CLOCK_BOOTTIME - constant missing in freepascal + CLOCK_UPTIME=CLOCK_MONOTONIC; + CLOCK_UPTIME_FAST=CLOCK_MONOTONIC_COARSE; + {$endif} + + {$ifdef freebsd} + CLOCK_REALTIME=freebsd.CLOCK_REALTIME; + CLOCK_MONOTONIC=freebsd.CLOCK_MONOTONIC; + CLOCK_REALTIME_COARSE=freebsd.CLOCK_REALTIME_FAST; + CLOCK_MONOTONIC_COARSE=freebsd.CLOCK_MONOTONIC_FAST; + CLOCK_BOOTTIME=CLOCK_MONOTONIC; + CLOCK_UPTIME=freebsd.CLOCK_UPTIME; + CLOCK_UPTIME_FAST=freebsd.CLOCK_UPTIME_FAST; + {$endif} + + {$ifdef darwin} + CLOCK_REALTIME=0; //values taken from darwin libc time.h + CLOCK_MONOTONIC=6; + CLOCK_REALTIME_COARSE=CLOCK_REALTIME; //darwin lacks these or equivalents + CLOCK_MONOTONIC_COARSE=CLOCK_MONOTONIC; + CLOCK_BOOTTIME=CLOCK_MONOTONIC; + CLOCK_UPTIME_RAW=8; + CLOCK_UPTIME=CLOCK_UPTIME_RAW; + CLOCK_UPTIME_FAST=CLOCK_UPTIME_RAW; + {$endif} + + CLOCK_REALTIME_FAST=CLOCK_REALTIME_COARSE; + CLOCK_MONOTONIC_FAST=CLOCK_MONOTONIC_COARSE; + + var timezone:integer; timezonestr:string; irctime,unixtime:tunixtimeint; tickcount:integer; settimebias:tunixtimeint; - performancecountfreq:extended; + performancecountfreq:int64; + performancecountstep:float; + btimenowin8:boolean; function irctimefloat:float; @@ -48,9 +138,20 @@ function unixtimeint:tunixtimeint; //monotonic float seconds function monotimefloat:float; +//coarse float seconds - usually faster, but a resolution in the milliseconds +function unixtimefloat_coarse:float; +function monotimefloat_coarse:float; + +//float versions of CLOCK_BOOTTIME and CLOCK_UPTIME +function boottimefloat:float; +function uptimefloat:float; + //monotonic (alias, old function name) function wintimefloat:float; +//get localtime vs UTC offset in seconds +function tzgetoffset:integer; + procedure settime(newtime:tunixtimeint); procedure gettimezone; procedure timehandler; @@ -80,11 +181,12 @@ function unixtoole(i:float):tdatetime; {$ifdef mswindows} function mmtimefloat:float; +function mmtimeint64:int64; function qpctimefloat:float; {$endif} {$ifdef mswindows} -procedure gettimeofday(var tv:ttimeval); +function gettimeofday(var tv:ttimeval):integer; {$endif} @@ -105,7 +207,7 @@ var lastsyncbias:float=0; mmtime_last:integer=0; - mmtime_wrapadd:float; + mmtime_wrapadd:int64; mmtime_lastsyncmm:float=0; mmtime_lastsyncqpc:float=0; mmtime_drift:float=1; @@ -118,17 +220,29 @@ var mmtime_prev_lastsyncmm:float; mmtime_prev_lastsyncqpc:float; -implementation + gettime64_nosupport_cached:boolean; + coarse_nosupport_cached:boolean; +type + //i define my own "timespec" and "gettime" because that way, they can be 64 bits even if the real one is 32 bits, and avoid the wrong one being used. + //tbtimespec can't be changed because it is passed as-is to clock_gettime64 + tbtimespec=packed record + tv_sec:int64; + tv_nsec:int64; + end; + pbtimespec=^tbtimespec; +//on unix, btime_gettime is the "inner" function that calls the actual OS/library functions, and other functions in btime call it +//on windows, btime_gettime is an "outer" function that calls the other functions. so if not called by the app, it does not add to exe size. +function btime_gettime(clockid:integer;tp:pbtimespec):integer; + +implementation uses {$ifdef UNIX} {$ifdef VER1_0} linux, {$else} - {$ifdef linux}linux,{$endif} //for clock_gettime - {$ifdef freebsd}freebsd,{$endif} //for clock_gettime baseunix,unix,unixutil,sockets, {unixutil and sockets needed by unixstuff.inc on some compiler versions} {$endif} {$else} @@ -158,117 +272,204 @@ begin result := ((i)/86400)+daysdifference; end; -const - highdwordconst=65536.0 * 65536.0; - -function utrunc(f:float):integer; -{converts float to integer, in 32 bits unsigned range} -begin - if f >= (highdwordconst/2) then f := f - highdwordconst; - result := trunc(f); -end; - -function uinttofloat(i:integer):float; -{converts 32 bits unsigned integer to float} -begin - result := i; - if result < 0 then result := result + highdwordconst; -end; - {$ifdef unix} {-----------------------------------------*nix/freepascal code to read time } -function unixtimefloat:float; -var - tv:ttimeval; - sec:tunixtimeint; -begin - gettimeofday(tv); - sec := tv.tv_sec; - {$ifndef cpu64} - if (sec < -1) then inc(sec,$100000000); //tv_sec is 32 bits. allow -1 for invalid result - {$endif} - result := sec+(tv.tv_usec/1000000); -end; - {$ifdef linux}{$define have_clock_gettime}{$endif} {$ifdef freebsd}{$define have_clock_gettime}{$endif} -{$ifdef have_clock_gettime} - {$define monotimefloat_implemented} +{$ifdef linux} + {$ifdef cpu386}{$define use_syscall_gettime64}{$endif} + {$ifdef cpu32}{$define use_syscall_gettime64}{$endif} - function monotimefloat:float; - var - ts: ttimespec; - begin - if clock_gettime(CLOCK_MONOTONIC, @ts) = 0 then begin - //note this really returns nanoseconds - result := ts.tv_sec + ts.tv_nsec / 1000000000.0; - exit; - end; - //fallback - result := unixtimefloat; - end; + {$ifdef use_syscall_gettime64} +const + clock_gettime64=403; + {$endif} +{$endif} //linux -{$endif} {$ifdef darwin} {mac OS X} -{$define monotimefloat_implemented} - type tmach_timebase_info = packed record - numer: longint; - denom: longint; + numer: cardinal; + denom: cardinal; end; pmach_timebase_info = ^tmach_timebase_info; - + function mach_absolute_time: int64; cdecl; external; function mach_timebase_info(info: pmach_timebase_info): integer; cdecl; external; var timebase_info: tmach_timebase_info; +{$endif} //darwin - function monotimefloat:float; - var - i:int64; - begin + +function btime_gettime(clockid:integer;tp:pbtimespec):integer; +var +{$ifdef have_clock_gettime} + ts: ttimespec; +{$endif} + tv: ttimeval; +{$ifdef darwin} + nanos:int64; + nanosf:extended; +{$endif} + +begin + result := -1; //error + + {$ifdef darwin} + if (clockid = CLOCK_MONOTONIC) or (clockid = CLOCK_MONOTONIC_COARSE) then begin if timebase_info.denom = 0 then begin mach_timebase_info(@timebase_info); end; - i := mach_absolute_time; - result := (i * timebase_info.numer div timebase_info.denom) / 1000000000.0; + if (timebase_info.denom > 0) then begin + nanos := mach_absolute_time; + if (nanos > 0) then begin + result := 0; //indicate success + if (timebase_info.denom > 10) then begin + //on powerpc mac, numer and denom are large numbers such as 1000000000 and 33333335, and extended is available + nanosf := nanos; + nanosf := (nanosf * timebase_info.numer) / timebase_info.denom; + nanos := trunc(nanosf); + end else begin + //on intel mac, numer and denom are 1 and 1. on apple silicon they are typically 125 and 3, and extended is not available + nanos := nanos div timebase_info.denom; + nanos := nanos * timebase_info.numer; + end; + tp.tv_sec := nanos div 1000000000; + tp.tv_nsec := nanos mod 1000000000; + exit; + end; + end; end; + {$endif} //darwin -{$endif} {darwin, mac OS X} + if (coarse_nosupport_cached) then begin + if (clockid = CLOCK_REALTIME_COARSE) then clockid := CLOCK_REALTIME; + if (clockid = CLOCK_MONOTONIC_COARSE) then clockid := CLOCK_MONOTONIC; + end; + {$ifdef use_syscall_gettime64} + //don't do this for monotonic for performance reasons + //the clock_gettime call below has the potential to be handled by libc, and then it is faster + //also if it failed, don't call it again to avoid slowdown of doing two calls every time + if (not ((clockid = CLOCK_MONOTONIC) or (clockid = CLOCK_MONOTONIC_COARSE) or (clockid = CLOCK_BOOTTIME) or (clockid = CLOCK_UPTIME))) and (not gettime64_nosupport_cached) then begin + result := do_syscall(clock_gettime64,clockid,tsysparam(tp)); -{$ifndef monotimefloat_implemented} {fallback} - - function monotimefloat:extended; - begin - result := unixtimefloat; + if ((clockid = CLOCK_REALTIME) or (clockid = CLOCK_REALTIME_COARSE)) and (result <> 0) then gettime64_nosupport_cached := true; + + if (result = 0) then exit; + end; + {$endif} + + {$ifdef have_clock_gettime} + result := clock_gettime(clockid, @ts); + if (result <> 0) then begin + //fallback + if (clockid = CLOCK_REALTIME_COARSE) then begin + coarse_nosupport_cached := true; + result := clock_gettime(CLOCK_REALTIME, @ts); + end else + if (clockid = CLOCK_MONOTONIC_COARSE) then begin + coarse_nosupport_cached := true; + result := clock_gettime(CLOCK_MONOTONIC, @ts); + end; end; + if (result = 0) then begin + tp.tv_sec := ts.tv_sec; + tp.tv_nsec := ts.tv_nsec; -{$endif} {monotimefloat fallback} + {$ifndef cpu64} + if (tp.tv_sec < -1) then inc(tp.tv_sec, $100000000); + {$endif} + + exit; + end; + {$endif} //have_clock_gettime + + result := gettimeofday(tv); + if (result = 0) then begin + tp.tv_sec := tv.tv_sec; + tp.tv_nsec := tv.tv_usec * 1000; + + {$ifndef cpu64} + if (tp.tv_sec < -1) then inc(tp.tv_sec, $100000000); + {$endif} + end; +end; + + +function unixtimefloat:float; +var + ts:tbtimespec; +begin + btime_gettime(CLOCK_REALTIME, @ts); + //doing the below as a division causes a bug in fpc 3.2.0 x64, where the result becomes single precision + result := ts.tv_sec + (ts.tv_nsec * 0.000000001); +end; + + +function monotimefloat:float; +var + ts:tbtimespec; +begin + btime_gettime(CLOCK_MONOTONIC, @ts); + result := ts.tv_sec + (ts.tv_nsec * 0.000000001); +end; + + +function unixtimefloat_coarse:float; +var + ts:tbtimespec; +begin + btime_gettime(CLOCK_REALTIME_COARSE, @ts); + result := ts.tv_sec + (ts.tv_nsec * 0.000000001); +end; + + +function monotimefloat_coarse:float; +var + ts:tbtimespec; +begin + btime_gettime(CLOCK_MONOTONIC_COARSE, @ts); + result := ts.tv_sec + (ts.tv_nsec * 0.000000001); +end; + + +function boottimefloat:float; +var + ts:tbtimespec; +begin + btime_gettime(CLOCK_BOOTTIME, @ts); + result := ts.tv_sec + (ts.tv_nsec * 0.000000001); +end; + + +function uptimefloat:float; +var + ts:tbtimespec; +begin + btime_gettime(CLOCK_UPTIME, @ts); + result := ts.tv_sec + (ts.tv_nsec * 0.000000001); +end; function unixtimeint:tunixtimeint; var - tv:ttimeval; - sec:tunixtimeint; + ts:tbtimespec; begin - gettimeofday(tv); - sec := tv.tv_sec; - {$ifndef cpu64} - if (sec < -1) then inc(sec,$100000000); //tv_sec is 32 bits. allow -1 for invalid result - {$endif} - result := sec; + btime_gettime(CLOCK_REALTIME,@ts); + result := ts.tv_sec; end; {------------------------------ end of *nix/freepascal section} -{$else} {windows} +{$endif} //unix + +{$ifdef mswindows} {------------------------------ windows/delphi code to read time} @@ -277,18 +478,39 @@ begin gettimezone; end; -{simulate gettimeofday on windows so one can always use gettimeofday if preferred} -procedure gettimeofday(var tv:ttimeval); var - e:extended; + GetTickCount64:function:int64; stdcall; + gettickcount64_inited:boolean; + +procedure init_gettickcount64; +var + dllhandle:thandle; begin - e := unixtimefloat; - tv.tv_sec := round(int(e)); - tv.tv_usec := trunc(frac(e)*1000000); - {just in case} - if (tv.tv_usec < 0) then tv.tv_usec := 0; - if (tv.tv_usec > 999999) then tv.tv_usec := 999999; + gettickcount64_inited := true; + dllhandle := loadlibrary('kernel32.dll'); + if (dllhandle <> 0) then begin + GetTickCount64 := getprocaddress(dllhandle,'GetTickCount64'); + end; +end; + + + +function mmtimeint64:int64; +var + i:int64; +begin + if not gettickcount64_inited then init_gettickcount64; + if assigned(GetTickCount64) then begin + result := GetTickCount64; + end else begin + i := gettickcount; + if i < mmtime_last then begin + mmtime_wrapadd := mmtime_wrapadd + $100000000; + end; + mmtime_last := i; + result := mmtime_wrapadd + i; + end; end; @@ -298,23 +520,12 @@ resolution: 9x: ~55 ms NT: 1/64th of a second guarantees: continuous without any jumps frequency base: same as system clock. epoch: system boot -note: if called more than once per 49.7 days, 32 bits wrapping is compensated for and it keeps going on. -note: i handle the timestamp as signed integer, but with the wrap compensation that works as well, and is faster } - function mmtimefloat:float; -const - wrapduration=highdwordconst * 0.001; var - i:integer; temp:float; begin - i := gettickcount; {timegettime} - if i < mmtime_last then begin - mmtime_wrapadd := mmtime_wrapadd + wrapduration; - end; - mmtime_last := i; - result := mmtime_wrapadd + i * 0.001; + result := mmtimeint64 * 0.001; if (ticks_freq <> 0) and ticks_freq_known then begin {the value we get is rounded to 1 ms, but the ticks are not a multiple of 1 ms @@ -329,14 +540,34 @@ begin end; end; +var + win_version_known:boolean; + win_isnt:boolean; + win_ver_major:integer; + win_ver_minor:integer; + +procedure init_win_version; +var + o:tosversioninfo; +begin + if not win_version_known then begin + win_version_known := true; + fillchar(o,sizeof(o),0); + o.dwOSVersionInfoSize := sizeof(o); + getversionex(o); + win_isnt := o.dwPlatformId = VER_PLATFORM_WIN32_NT; + win_ver_major := o.dwMajorVersion; + win_ver_minor := o.dwMinorVersion; + end; +end; + procedure measure_ticks_freq; var f,g:float; - o:tosversioninfo; - isnt:boolean; -{ is9x:boolean;} + adjust1,adjust2:cardinal; adjustbool:longbool; + win8_or_later:boolean; begin if (performancecountfreq = 0) then qpctimefloat; ticks_freq_known := false; @@ -345,22 +576,26 @@ begin repeat g := mmtimefloat until g > f; unsettc; f := g - f; - fillchar(o,sizeof(o),0); - o.dwOSVersionInfoSize := sizeof(o); - getversionex(o); - isnt := o.dwPlatformId = VER_PLATFORM_WIN32_NT; -{ is9x := o.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS;} + + init_win_version; ticks_freq2 := f; mmtime_synchedqpc := false; - if (isnt and (o.dwMajorVersion >= 5)) then begin + if (win_isnt and (win_ver_major >= 5)) then begin {windows 2000 and later: query tick rate from OS in 100 ns units typical rates: XP: 156250 or 100144, windows 7: 156001} if GetSystemTimeAdjustment(adjust1,adjust2,adjustbool) then begin ticks_freq := adjust1 / 10000000.0; ticks_freq_known := true; mmtime_synchedqpc := false; + + //windows 8/10/11, 10 MHz time source is invariant TSC. add 64 Hz check for safety. + //with manifest, windows 10/11 major.minor will be 10.0 + win8_or_later := ((win_ver_major = 6) and (win_ver_minor >= 2)) or (win_ver_major = 10); + if (win8_or_later and (performancecountfreq = 10000000) and (adjust1 = 156250)) then begin + mmtime_synchedqpc := true; + end; end; end; @@ -382,26 +617,16 @@ guarantees: can have forward jumps depending on hardware. can have forward and b frequency base: on NT, not the system clock, drifts compared to it. epoch: system boot } -function qpctimefloat:extended; +function qpctimefloat:float; var - p:packed record - lowpart:longint; - highpart:longint - end; - p2:tlargeinteger absolute p; - e:extended; + i64:int64; begin if performancecountfreq = 0 then begin - QueryPerformancefrequency(p2); - e := p.lowpart; - if e < 0 then e := e + highdwordconst; - performancecountfreq := ((p.highpart*highdwordconst)+e); + QueryPerformancefrequency(performancecountfreq); + performancecountstep := 1.0 / performancecountfreq; end; - queryperformancecounter(p2); - e := p.lowpart; - if e < 0 then e := e + highdwordconst; - - result := ((p.highpart*highdwordconst)+e)/performancecountfreq; + queryperformancecounter(i64); + result := i64 * performancecountstep; end; { @@ -412,7 +637,8 @@ frequency base: same as system clock. epoch: system boot } -function mmqpctimefloat:float; +//function mmqpctimefloat:float; +function monotimefloat:float; const maxretries=5; margin=0.002; @@ -504,63 +730,47 @@ begin mmtime_lastresult := result; end; -{ free pascals tsystemtime is incompatible with windows api calls - so we declare it ourselves - plugwash -} -{$ifdef fpc} -type - TSystemTime = record - wYear: Word; - wMonth: Word; - wDayOfWeek: Word; - wDay: Word; - wHour: Word; - wMinute: Word; - wSecond: Word; - wMilliseconds: Word; - end; - {$endif} -function Date_utc: extended; -var - SystemTime: TSystemTime; + +function boottimefloat:float; begin - {$ifdef fpc} - GetsystemTime(@SystemTime); - {$else} - GetsystemTime(SystemTime); - {$endif} - with SystemTime do Result := EncodeDate(wYear, wMonth, wDay); + result := monotimefloat; end; -function Time_utc: extended; var - SystemTime: TSystemTime; -begin - {$ifdef fpc} - GetsystemTime(@SystemTime); - {$else} - GetsystemTime(SystemTime); - {$endif} - with SystemTime do - Result := EncodeTime(wHour, wMinute, wSecond, wMilliSeconds); -end; + QueryUnbiasedInterruptTime:function(var i:int64):longbool; stdcall; + unbiasedinterrupttime_inited:boolean; + -function Now_utc: extended; +procedure initunbiasedinterrupttime; +var + dllhandle:thandle; begin - Result := round(Date_utc) + Time_utc; + unbiasedinterrupttime_inited := true; + dllhandle := loadlibrary('kernel32.dll'); + if (dllhandle <> 0) then begin + QueryUnbiasedInterruptTime := getprocaddress(dllhandle,'QueryUnbiasedInterruptTime'); + end; end; -function unixtimefloat_systemtime:float; +function unbiasedtime_100ns:int64; begin - {result := oletounixfloat(now_utc);} - - {this method gives exactly the same result with extended precision, but is less sensitive to float rounding in theory} - result := oletounixfloat(int(date_utc+0.5))+time_utc*86400; + result := -1; + if not unbiasedinterrupttime_inited then initunbiasedinterrupttime; + if assigned(@QueryUnbiasedInterruptTime) then begin + QueryUnbiasedInterruptTime(result); + end; end; -function monotimefloat:extended; +function uptimefloat:float; +var + i:int64; begin - result := mmqpctimefloat; + i := unbiasedtime_100ns; + if (i > 0) then begin + result := i * 0.0000001; + exit; + end; + result := qpctimefloat; end; @@ -582,16 +792,167 @@ begin end; -function unixtimefloat_win8:float; +function win8time_as_unix_100ns:int64; +var + ft:tfiletime; + i:int64 absolute ft; +begin + result := -1; + if not win8inited then initwin8; + if assigned(@GetSystemTimePreciseAsFileTime) then begin + GetSystemTimePreciseAsFileTime(ft); + //change from windows 1601-01-01 to unix 1970-01-01. + dec(i, 116444736000000000); + result := i; + end; +end; + + +function unixtimefloat_systemtime:float; var ft:tfiletime; i:int64 absolute ft; begin - GetSystemTimePreciseAsFileTime(ft); - {change from windows 1601-01-01 to unix 1970-01-01. - use integer math for this, to preserve precision} + //result := oletounixfloat(now_utc); + + //this method gives exactly the same result with extended precision, but is less sensitive to float rounding in theory} + //result := oletounixfloat(int(date_utc+0.5))+time_utc*86400; + + //new method that is much faster (22 vs 190 ns) + GetSystemTimeAsFileTime(ft); dec(i, 116444736000000000); - result := (i / 10000000); + result := i * 0.0000001; +end; + + +function unixtimefloat_coarse:float; +begin + //don't do the coarse method if worse than about 16 ms. on win9x it may be only a 55 ms resolution + //but i have also seen it is less (like 1 ms) + //don't call measure_ticks_freq on NT because it is expensive and unnecessary + init_win_version; + if not win_isnt then begin + if not ticks_freq_known then measure_ticks_freq; + end; + if win_isnt or (ticks_freq < 0.017) then begin + result := unixtimefloat_systemtime; + exit; + end; + + result := unixtimefloat; +end; + +function monotimefloat_coarse:float; +begin + init_win_version; + if not win_isnt then begin + if not ticks_freq_known then measure_ticks_freq; + end; + if win_isnt or (ticks_freq < 0.017) then begin + result := mmtimeint64 * 0.001; + exit; + end; + result := monotimefloat; +end; + + +//simulate gettimeofday on windows so one can always use gettimeofday if preferred +function gettimeofday(var tv:ttimeval):integer; +var + e:float; + i:int64; +begin + result := -1; + + if not btimenowin8 then begin + i := win8time_as_unix_100ns; + if (i > 0) then begin + tv.tv_sec := i div 10000000; + tv.tv_usec := (i mod 10000000) div 10; + result := 0; + exit; + end; + end; + + e := unixtimefloat; + if (e > 0) then result := 0; + tv.tv_sec := trunc(e); + tv.tv_usec := trunc(frac(e)*1000000); +end; + + +function btime_gettime(clockid:integer;tp:pbtimespec):integer; +var + f:float; + i:int64; + +{$ifdef cpu386}{$ifdef has_extended}{$define itotp_float}{$endif}{$endif} +procedure i100ns_to_tp_and_success; +{$ifdef itotp_float} +var + f:float; +{$endif} +begin + //in 32 bits delphi, float is 10 times faster than int64 here (30 vs 300 ns for the conversion) + //and with extended available, there is no loss of precision + + {$ifdef itotp_float} + f := i / 10000000.0; + tp.tv_sec := trunc(f); + tp.tv_nsec := round(frac(f) * 1000000000.0); + {$else} + tp.tv_sec := i div 10000000; + tp.tv_nsec := (i mod 10000000) * 100; + {$endif} + + result := 0; //success +end; + +procedure f_to_tp_and_success; +begin + tp.tv_sec := trunc(f); + tp.tv_nsec := round(frac(f) * 1000000000.0); + result := 0; //success +end; + +begin + result := -1; //error + + case clockid of + CLOCK_REALTIME: begin + //implement this case directly for full precision even without extended floats + if not btimenowin8 then begin + i := win8time_as_unix_100ns; + if (i > 0) then begin + i100ns_to_tp_and_success; + exit; + end; + end; + f := unixtimefloat; + f_to_tp_and_success; + end; + CLOCK_MONOTONIC: begin + f := monotimefloat; + f_to_tp_and_success; + end; + CLOCK_REALTIME_COARSE: begin + f := unixtimefloat_coarse; + f_to_tp_and_success; + end; + CLOCK_MONOTONIC_COARSE: begin + f := monotimefloat_coarse; + f_to_tp_and_success; + end; + CLOCK_UPTIME: begin + i := unbiasedtime_100ns; + if (i > 0) then begin + i100ns_to_tp_and_success; + exit; + end; + f := qpctimefloat; + f_to_tp_and_success; + end; + end; end; @@ -603,17 +964,13 @@ var f,g,h:float; begin if not btimenowin8 then begin - if not win8inited then initwin8; - if assigned(@GetSystemTimePreciseAsFileTime) then begin - result := unixtimefloat_win8; - exit; - end; + result := win8time_as_unix_100ns * 0.0000001; + if (result > 0) then exit; end; result := monotimefloat+timefloatbias; f := result-unixtimefloat_systemtime; if ((f > ticks_freq2+margin) or (f < -margin)) or (timefloatbias = 0) then begin -// writeln('unixtimefloat init'); f := unixtimefloat_systemtime; settc; repeat g := unixtimefloat_systemtime; h := monotimefloat until g > f; @@ -622,8 +979,8 @@ begin result := unixtimefloat; end; - {for small changes backwards, guarantee no steps backwards} - if (result <= lastunixtimefloat) and (result > lastunixtimefloat-1.5) then result := lastunixtimefloat + 0.0000001; + //for small changes backwards, guarantee no steps backwards + if (result <= lastunixtimefloat) and (result > lastunixtimefloat-1.5) then result := lastunixtimefloat; lastunixtimefloat := result; end; @@ -632,7 +989,7 @@ begin result := trunc(unixtimefloat); end; -{$endif} +{$endif} //mswindows {-----------------------------------------------end of platform specific} function wintimefloat:float; @@ -665,7 +1022,7 @@ procedure timehandler; begin if unixtime = 0 then init; unixtime := unixtimeint; - irctime := irctimeint; + irctime := unixtime+settimebias; if unixtime and 63 = 0 then begin {update everything, apply timezone changes, clock changes, etc} gettimezone; @@ -685,18 +1042,28 @@ var function tzgetfilename:ansistring; var t:textfile; - + a:integer; s,tz,tzdir:ansistring; + ispath:boolean; begin result := ''; filemode := 0; - {$ifdef unix} + tz := getenv('TZ'); - if (copy(tz,1,1) = ':') then begin - tz := copy(tz,2,99999); + if (tz <> '') then begin + ispath := false; + if (copy(tz,1,1) = ':') then begin + ispath := true; + tz := copy(tz,2,99999); + end; if (copy(tz,1,1) <> '/') then begin + a := pos(',',tz); + if (a > 1) and not ispath then begin + tz := copy(tz,1,a-1); + end; + tzdir := getenv('TZDIR'); if (tzdir = '') then begin tzdir := '/usr/share/zoneinfo/'; @@ -715,8 +1082,7 @@ begin end; end; - {$endif} - + assignfile(t,'/etc/localtime'); {$i-}reset(t);{$i+} if (ioresult = 0) then begin @@ -724,19 +1090,6 @@ begin result := '/etc/localtime'; exit; end; - - assignfile(t,'/etc/timezone'); - - s := ''; - {$i-}reset(t);{$i+} - if (ioresult = 0) then begin - readln(t,s); - closefile(t); - if (s <> '') then begin - result := '/usr/share/zoneinfo/'+s; - exit; - end; - end; end; type @@ -891,17 +1244,9 @@ begin end; end; -function tzgetoffset:integer; -begin - tzgetoffsetforts(unixtimeint); -end; - - -{$endif} - +{$endif} //unix -procedure gettimezone; -var +function tzgetoffset:integer; {$ifdef UNIX} {$ifndef ver1_9_4} {$ifndef ver1_0} @@ -909,25 +1254,46 @@ var {$endif} {$endif} {$ifndef above194} +var hh,mm,ss:word; {$endif} + {$else} +var + TimeZoneInfo: TIME_ZONE_INFORMATION; + tztype:cardinal; + min:integer; {$endif} - l:integer; + begin {$ifdef UNIX} {$ifdef above194} - timezone := tzgetoffset; + result := tzgetoffsetforts(unixtimeint); //freepascal tzseconds is not 2038 safe {$else} gettime(hh,mm,ss); - timezone := (longint(hh) * 3600 + mm * 60 + ss) - (unixtimeint mod 86400); + result := (integer(hh) * 3600 + mm * 60 + ss) - (unixtimeint mod 86400); {$endif} {$else} - timezone := round((now-now_utc)*86400); + tztype := GetTimeZoneInformation(TimeZoneInfo); + min := TimeZoneInfo.Bias; + case tztype of + //TIME_ZONE_ID_UNKNOWN: don't add DST + TIME_ZONE_ID_STANDARD: inc(min, TimeZoneInfo.StandardBias); + TIME_ZONE_ID_DAYLIGHT: inc(min, TimeZoneInfo.DaylightBias); + end; + result := min * -60; {$endif} - while timezone > 50400 do dec(timezone,86400); - while timezone < -50400 do inc(timezone,86400); + while result > (14 * 3600) do dec(result,86400); + while result < -(14 * 3600) do inc(result,86400); +end; + + +procedure gettimezone; +var + l:integer; +begin + timezone := tzgetoffset; if timezone >= 0 then timezonestr := '+' else timezonestr := '-'; l := abs(timezone) div 60; diff --git a/ltimevalstuff.pas b/ltimevalstuff.pas index 7a10c7a..da8bb94 100644 --- a/ltimevalstuff.pas +++ b/ltimevalstuff.pas @@ -10,11 +10,19 @@ unit ltimevalstuff; interface + +{$ifdef CONDITIONALEXPRESSIONS}{$define support_int64}{$endif} //delphi 6 or later +{$ifdef fpc}{$define support_int64}{$endif} + {$ifdef mswindows} type ttimeval = record - tv_sec : longint; - tv_usec : longint; + {$IFDEF support_int64} + tv_sec : int64; + {$ELSE} + tv_sec : longint; + {$ENDIF} + tv_usec : longint; end; {$else} {$ifdef ver1_0} diff --git a/unixstuff.inc b/unixstuff.inc index 1a9a97b..ae615ff 100644 --- a/unixstuff.inc +++ b/unixstuff.inc @@ -125,9 +125,9 @@ end; {$define need_v6constants} {$endif} - procedure gettimeofday(var tv:ttimeval);inline; + function gettimeofday(var tv:ttimeval):integer; inline; begin - fpgettimeofday(@tv,nil); + result := fpgettimeofday(@tv,nil); end; function gettimeofdaysec : longint; var -- 2.30.2