Notes & TILs
Search…
Measure Exection time in Go
To know who how long your go code executes you can use the time.Now() and time.Since() methods in the time package.

Demo

1
package main
2
​
3
import (
4
"fmt"
5
"time"
6
)
7
​
8
func main(){
9
​
10
start := time.Now()
11
dur, _ := time.ParseDuration("15ms")
12
​
13
// A Go Anonymous function (self-executing)
14
func (){
15
for i := 0; i < 100; i++ {
16
time.Sleep(dur)
17
fmt.Println("Bhupesh is programming in Go")
18
}
19
}()
20
​
21
elapsed := time.Since(start)
22
​
23
fmt.Printf("Execution Time : %s", elapsed)
24
}
Copied!
Since() returns the time elapsed since t (start in our demo). It is shorthand for time.Now().Sub(t).
Here is the output of the above code You can also play with the online demo
1
Bhupesh is programming in Go
2
Bhupesh is programming in Go
3
Bhupesh is programming in Go
4
Bhupesh is programming in Go
5
Bhupesh is programming in Go
6
Bhupesh is programming in Go
7
Bhupesh is programming in Go
8
Bhupesh is programming in Go
9
Bhupesh is programming in Go
10
Bhupesh is programming in Go
11
Bhupesh is programming in Go
12
Bhupesh is programming in Go
13
Bhupesh is programming in Go
14
Bhupesh is programming in Go
15
Bhupesh is programming in Go
16
Bhupesh is programming in Go
17
Bhupesh is programming in Go
18
Bhupesh is programming in Go
19
Bhupesh is programming in Go
20
Bhupesh is programming in Go
21
Bhupesh is programming in Go
22
Bhupesh is programming in Go
23
Bhupesh is programming in Go
24
Bhupesh is programming in Go
25
Bhupesh is programming in Go
26
Bhupesh is programming in Go
27
Bhupesh is programming in Go
28
Bhupesh is programming in Go
29
Bhupesh is programming in Go
30
Bhupesh is programming in Go
31
Bhupesh is programming in Go
32
Bhupesh is programming in Go
33
Bhupesh is programming in Go
34
Bhupesh is programming in Go
35
Bhupesh is programming in Go
36
Bhupesh is programming in Go
37
Bhupesh is programming in Go
38
Bhupesh is programming in Go
39
Bhupesh is programming in Go
40
Bhupesh is programming in Go
41
Bhupesh is programming in Go
42
Bhupesh is programming in Go
43
Bhupesh is programming in Go
44
Bhupesh is programming in Go
45
Bhupesh is programming in Go
46
Bhupesh is programming in Go
47
Bhupesh is programming in Go
48
Bhupesh is programming in Go
49
Bhupesh is programming in Go
50
Bhupesh is programming in Go
51
Execution Time : 750ms
Copied!
Last modified 1mo ago
Copy link
Contents
Demo