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)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay