Published on

Measure Execution Time in Go

Simple timing

Quick and dirty timing of a code

start := time.Now()

// Code to measure here

duration := time.Since(start)
fmt.Println(duration)

Function call

func foo() {
    defer TrackMeasuring(time.Now(), "trackFoo")
    // Code to measure here
}
func TrackMeasuring(start time.Time, name string) {
	log.Printf("%s took %s\n", name, time.Since(start))
}

Callback function

func foo(){
    TrackMeasuring("trackBar", func(){
        bar()
    })
}
func bar(){
    // Code to measure here
}
func TrackMeasuring(name string, f func()) {
	start := time.Now()
	defer func() {
		log.Printf("%s took %s\n", name, time.Since(start))
	}()
	f()
}