Go (Golang) is fast. This phrase is everywhere. It’s always interesting how long it takes a function to finish its operation.

Here is an example of a helper function, that could be used to check and log the timing:

func TimeTrack(start time.Time, name string) {
	elapsed := time.Since(start)
	log.Printf("%s took %s", name, elapsed)
}

It takes a start time and the name (could be a function name) as parameters.

Use it with the “defer” statement inside the functions:

func dosomething() {
	defer TimeTrack(time.Now(), "dosomething Function")
	time.Sleep(time.Millisecond * 1000)
	fmt.Println("Printing inside dosomething")
}

ps:  a defer statement defers the execution of a function until the surrounding function returns.

Example with the main function:

func main() {
	defer TimeTrack(time.Now(), "Main Function")
	dosomething()
}

As a result, the output would be:

Printing inside dosomething
2009/11/10 23:00:01 dosomething Function took 1s
2009/11/10 23:00:02 Main Function took 1s