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 mainimport ("log""time")func main() {start := time.Now().UnixNano() / int64(time.Millisecond)// do somethingtime.Sleep(1 * time.Second)end := time.Now().UnixNano() / int64(time.Millisecond)diff := end - startlog.Printf("Duration(ms): %d", diff)}
Explanation
-
Lines 2–5: We import the necessary packages for the code. The
logobject is used to display output to the console, and thetimeobject 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 theUnixNano()to get the milliseconds value and divide it byint64(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
endvariable. We delay the execution time in line 9 by 1000 milliseconds. Therefore, we have theendvariable a 1000 milliseconds greater thanstart. -
Line 11: Next, we find the difference between the two times by subtracting the
endfrom thestartand saving it in thediffvariable. -
Line 12: We call the
logpackage and usePrintfto display our output.