DEV Community

Nitin Bansal
Nitin Bansal

Posted on

One liner automatic method name and time-tracking of a function

#go

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()
}
Enter fullscreen mode Exit fullscreen mode

> 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()
}
Enter fullscreen mode Exit fullscreen mode

Enjoy... ☺️

Top comments (0)