"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Go time and its two clocks

Go time and its two clocks

Published on 2024-11-18
Browse:266

Go time and its two clocks

To calculate the time lapse in Go, you can use

start := time.Now()
// long time consuming task
duration := time.Since(start)

But do you know that the time package in Go actually has two times in it, and time.Since() actually measures only the processing time (monotonic clock), not the real time (wall clock)?

For example if the task is pretty long, overnight long, and your computer went to sleep. Then in the morning, you may come and see the duration last only 4 hours while in total 10 hours had been passed.

The time package in Go states that

Operating systems provide both a “wall clock,” which is subject to changes for clock synchronization, and a “monotonic clock,” which is not. The general rule is that the wall clock is for telling time and the monotonic clock is for measuring time.

What it really tells you in our above example is that your program actively ran for 4 hours, but the computer sleeps 6 hours, so in total you waited 10 hours. If the computer had not slept, it would be done in 4 hours.

So what to do if you want to measure the wall time? You can use the Round(0) function. t = t.Round(0) will remove the monotonic clock in t.

Release Statement This article is reproduced at: https://dev.to/jingshao_chen_02a2352f476/go-time-and-its-two-clocks-3p0p?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3