Created
July 6, 2020 02:55
-
-
Save evzpav/b98fd07d67daea4ceca8fb08ba075f38 to your computer and use it in GitHub Desktop.
Measure function time to execute in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func measureTime(funcName string) func() { | |
start := time.Now() | |
return func() { | |
fmt.Printf("Time taken by %s function is %v \n", funcName, time.Since(start)) | |
} | |
} | |
func expensivePrint() { | |
defer measureTime("expensivePrint")() | |
for i := 1; i <= 5; i++ { | |
fmt.Printf("Current number is %d \n", i) | |
time.Sleep(100 * time.Millisecond) | |
} | |
} | |
func main() { | |
expensivePrint() | |
fmt.Println("Finished executing main") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment