I have two function calls that I would like to separate by at least a nanosecond. But I want the delay to be as small as possible.
The code below shows an empty for loop is much more efficient at this than using time.Sleep(time.Nanosecond)
Is there an even more efficient way to guarantee at least one nanosecond has elapsed?
func TimeWaster () { start := uint64(time.Now().UnixNano()) stop := uint64(time.Now().UnixNano()) fmt.Println(time.Duration(stop-start))//0s //no nanoseconds pass start = uint64(time.Now().UnixNano()) time.Sleep(time.Nanosecond) stop = uint64(time.Now().UnixNano()) fmt.Println(time.Duration(stop-start))//6.9482ms //much *much* more than one nanosecond passes start = uint64(time.Now().UnixNano()) for uint64(time.Now().UnixNano()) == start { //intentionally empty loop } stop = uint64(time.Now().UnixNano()) fmt.Println(time.Duration(stop-start))//59.3µs //much quicker than time.Sleep(time.Nanosecond), but still much slower than 1 nanosecond }
https://stackoverflow.com/questions/66864007/what-is-the-most-time-efficient-way-to-guarantee-at-least-one-nanosecond-has-ela March 30, 2021 at 10:29AM
没有评论:
发表评论