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 …


This content originally appeared on DEV Community and was authored by Jingshao Chen

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.


This content originally appeared on DEV Community and was authored by Jingshao Chen


Print Share Comment Cite Upload Translate Updates
APA

Jingshao Chen | Sciencx (2024-09-21T16:36:48+00:00) Go time and its two clocks. Retrieved from https://www.scien.cx/2024/09/21/go-time-and-its-two-clocks/

MLA
" » Go time and its two clocks." Jingshao Chen | Sciencx - Saturday September 21, 2024, https://www.scien.cx/2024/09/21/go-time-and-its-two-clocks/
HARVARD
Jingshao Chen | Sciencx Saturday September 21, 2024 » Go time and its two clocks., viewed ,<https://www.scien.cx/2024/09/21/go-time-and-its-two-clocks/>
VANCOUVER
Jingshao Chen | Sciencx - » Go time and its two clocks. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/09/21/go-time-and-its-two-clocks/
CHICAGO
" » Go time and its two clocks." Jingshao Chen | Sciencx - Accessed . https://www.scien.cx/2024/09/21/go-time-and-its-two-clocks/
IEEE
" » Go time and its two clocks." Jingshao Chen | Sciencx [Online]. Available: https://www.scien.cx/2024/09/21/go-time-and-its-two-clocks/. [Accessed: ]
rf:citation
» Go time and its two clocks | Jingshao Chen | Sciencx | https://www.scien.cx/2024/09/21/go-time-and-its-two-clocks/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.