I like not to allow the code to repeat. But I have a situation, when I must repeat it in every function I want to measure execution time, and I can do nothing to it. For example, a function:
func someFunc() {
start_time := time.Now()
defer fmt.Println("Execution time: %v", time.Now().Sub(start_time))
<... doing some bussiness ...>
}
Now I must repeat this two first strokes in every function (and in original they are more complicated because of calling a function name). So I cannot make a function which measures time, because i must use defer inside of it. I cannot make a function even for second stroke, cause in original it calls a function name in Println and that's why the resulting name will not be of needed function. Is there any way to insert this code by some label or a template, for example, like this:
func someFunc() {
//go-insert measuretime.tmpl
<... doing some bussiness ...>
}
And measuretime.tmpl is:
start_time := time.Now()
defer fmt.Println("Execution time: %v", time.Now().Sub(start_time))
This trick might help: defer a call to a function returning a function enclosing the start time.
func elapsed() func() {
start := time.Now()
return func() {
fmt.Println("Duration was", time.Since(start))
}
}
Call it as follows:
defer elapsed()()
Having said that, benchmarking is the usual way to measure performance in Go. See how to write benchmarks in Go.