How to get milliseconds time difference in Golang

Overview

While developing an application, we often want to display to users how long a particular program takes to execute. Similarly, we would want a time difference set to tell us how long a code snippet took to execute. In this shot, we’ll take a look at a simple time difference code example.

Example

package main
import (
"log"
"time"
)
func main() {
start := time.Now().UnixNano() / int64(time.Millisecond)
// do something
time.Sleep(1 * time.Second)
end := time.Now().UnixNano() / int64(time.Millisecond)
diff := end - start
log.Printf("Duration(ms): %d", diff)
}

Explanation

  • Lines 2–5: We import the necessary packages for the code. The log object is used to display output to the console, and the time object is used to work with time.

  • Line 7: We use time.Now() to get the current time, and convert it to seconds using dot notation. Next, we attach the UnixNano() to get the milliseconds value and divide it by int64(time.Millisecond).

  • Line 9: We use time.Sleep(1 * time.Second) to pause the execution time between the code in line 7 and the code in line 10.

  • Line 10: We do the same thing we did in line 7, but we store the time in the end variable. We delay the execution time in line 9 by 1000 milliseconds. Therefore, we have the end variable a 1000 milliseconds greater than start.

  • Line 11: Next, we find the difference between the two times by subtracting the end from the start and saving it in the diff variable.

  • Line 12: We call the log package and use Printf to display our output.

Free Resources