Execution time measurement pitfall in Go
In Go, you can measure how long a process took like this:
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
time.Sleep(time.Second * 3)
elapsed := time.Since(now)
fmt.Printf("Took %s", elapsed) // Output: Took 3s
}
While the time package’s Duration type makes it easy to implement time measurement, some of its features are not intuitive.
The example above shows the function Since returns how many seconds elapsed. When the expected duration is much longer, let’s say it might take a couple of hours, you can use the method Hours:
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
time.Sleep(time.Second * 3)
elapsed := time.Since(now).Hours()
fmt.Printf("Took %v hours", elapsed)
}
What do you think the output will become? Some of you might think it will be 0
since it took just 3 seconds, less than an hour.
But the answer is 0.0008333333333333334
. Try it. The value’s type is float64 and it can be less than 1.
Other methods, Minutes and Seconds also return float64 value.
I’d suggest leaving a comment about this feature when you need them to help your colleague.