Go provides us with the time package to handle time and date related. In this article, we will cover how to measure the time elapsed between two-time instances.
Time.Duration
Duration refers to the time elapsed between two-time objects as an int64 nanosecond count. If we set the duration to 1000000000 nanoseconds, this represents 1 second or 1000 millisecond. The maximum duration we can represent (for int64) is 290 years.
The following the syntax definition for the duration in the time package.
The durations defined in the time package include:
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)
Note that the above values are constants.
In the time package, we can use the following function to return a duration:
Time.Sub()
The function syntax is as shown:
returns the duration t-u.
Time.Since()
The syntax for the Since() method is as shown:
This function returns duration passed since t.
Time.Until()
The syntax is as shown:
return the duration until t. Think of it as a shorthand for time.Sub(time.Now()).
Time.Duration
This function returns the duration in nanoseconds. The syntax is as shown:
func (d Duration) Milliseconds() int64
Example
The following code illustrates how to calculate the duration.
import (
"fmt"
"time"
)
func main() {
// set duration
var duration time.Duration = 1000000000
// in hours
fmt.Println(duration.Hours())
// minutes
fmt.Println(duration.Minutes())
// seconds
fmt.Println(duration.Seconds())
// milliseconds
fmt.Println(duration.Milliseconds())
// microseconds
fmt.Println(duration.Microseconds())
// using sub method
now := time.Now()
time.Sleep(1000)
diff := now.Sub(time.Now())
fmt.Println("Elapsed Seconds: ", diff.Seconds())
}
In the first section of the program, we create a duration and set it to 1000000000 nanoseconds. We then use the methods from the time package to convert it into various formats.
In the second section, we use the Sub() method to calculate the time difference after a sleep operation.
The code above should return:
0.0002777777777777778
0.016666666666666666
1
1000
1000000
Elapsed Seconds: -0.0072517
Conclusion
This article guides you to working with durations in the Go language as provided by the time package. For additional information, consider the documentation.