Correctly measure time duration in Go -
what correct way precisely measure time duration in go? application use standard time package , following approach:
var starttime = time.now() dosomehardwork() var duration = time.since(starttime) // or: time.now() - starttime
however, time.now()
returns current system time, leads 2 flaws:
- if system time changed during measurement (for example due time zone change (dst) or leap second), resulting duration wrong.
the system time can tick deliberately faster or slower real time. happens when operating system synchronizes internal clock ntp time servers (which might happen several times hour!)
from msdn:
[the time service] adjusts local clock rate allow converge toward correct time. if time difference between local clock , [accurate time sample] large correct adjusting local clock rate, time service sets local clock correct time.
if system time changes (either manually or due dst), might possible detect invalid duration , discard it. if system clock ticks e.g. 10% faster synchronize world-time, practically impossible detect. that's intended behaviour , how system clock designed.
for reason, other languages offer dedicated api measuring durations:
- java has
system.nanotime()
,system.currenttimemillis()
equivalenttime.now()
, wrong - c# has
system.diagnostics.stopwatch
- c/c++ on windows has
queryperformancecounter
,queryperformancefrequency
- c++11 , have
std::chrono::steady_clock
, orstd::chrono::high_resolution_clock
whenis_steady
member constanttrue
- javascript has
performance.now()
, while use ofnew date()
wrong
what correct way precisely measure execution time in go?
monotonic clocks
operating systems provide both “wall clock,” subject changes clock synchronization, , “monotonic clock,” not. general rule wall clock telling time , monotonic clock measuring time. rather split api, in package time returned time.now contains both wall clock reading , monotonic clock reading; later time-telling operations use wall clock reading, later time-measuring operations, comparisons , subtractions, use monotonic clock reading.
for example, code computes positive elapsed time of approximately 20 milliseconds, if wall clock changed during operation being timed:
start := time.now() ... operation takes 20 milliseconds ... t := time.now() elapsed := t.sub(start)
other idioms, such time.since(start), time.until(deadline), , time.now().before(deadline), robust against wall clock resets.
starting go 1.9 (released august 24, 2017), go uses monotonic clock durations.
Comments
Post a Comment