github.com/getlantern/mtime@v0.0.0-20200417132445-23682092d1f7/mtime.go (about) 1 // Package mtime provides time operations using a monotonic time source, which 2 // is useful when you want to work with elapsed rather than wall time. Based on 3 // github.com/aristanetworks/monotime. mtime uses Instants. INSTANTS ARE NOT 4 // REAL TIMES, they are only useful for measuring elapsed time. 5 package mtime 6 7 import ( 8 "time" 9 ) 10 11 // An Instant represents an instant in monotonically increasing time. INSTANTS 12 // ARE NOT REAL TIMES, they are only useful for measuring elapsed time. 13 type Instant uint64 14 15 // Add adds a duration to an Instant 16 func (i Instant) Add(d time.Duration) Instant { 17 return Instant(uint64(time.Duration(i) + d)) 18 } 19 20 // Sub subtracts an Instant from an Instant 21 func (i Instant) Sub(o Instant) time.Duration { 22 return time.Duration(i - o) 23 } 24 25 // Now() returns an instant in monotonic time 26 func Now() Instant { 27 return Instant(now()) 28 } 29 30 // Stopwatch starts a stopwatch and returns a function that itself returns the 31 // amount of time elapsed since the start of the stopwatch. 32 func Stopwatch() (elapsed func() time.Duration) { 33 start := Now() 34 return func() time.Duration { 35 return Now().Sub(start) 36 } 37 }