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:

  1. if system time changed during measurement (for example due time zone change (dst) or leap second), resulting duration wrong.
  2. 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:

what correct way precisely measure execution time in go?

package time

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.

see proposal: monotonic elapsed time measurements in go.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -