Simple and sweet one-liner to print time taken and function name automagically:
func takeSomeTime(){
defer un(trace())
time.Sleep(time.Second * 2)
}
func main(){
takeSomeTime()
}
>
2021/11/22 19:24:23 Time taken by 'main.takeSomeTime': 2.003439277s
Looking for the magic sauce?.... Here it is...
func un(name string, start time.Time){
log.Printf("Time taken by %s: %s", name, time.Now().Sub(start).String())
}
func trace() (string, time.Time) {
pc := make([]uintptr, 15)
n := runtime.Callers(2, pc)
frame, _ := runtime.CallersFrames(pc[:n]).Next()
return frame.Function, time.Now()
}
Enjoy... ☺️
Top comments (0)