Last Updated: February 25, 2016
·
952
· deckarep

Go: Timing a function call using defer

I can't take credit for this, but I just wanted to help spread the word. I was looking for a super easy way to time a function call with minimal effort. Well, I came across this post on stackoverflow.com and saw a great answer by amattn.

If you like this consider upvoting the original stackoverflow.com post: http://stackoverflow.com/questions/8350609/how-do-you-time-a-function-in-go-and-return-its-runtime-in-milliseconds

Here's the core concept:

In Go 1.x, define the following functions:

func trace(s string) (string, time.Time) {
    log.Println("START:", s)
    return s, time.Now()
}

func un(s string, startTime time.Time) {
    endTime := time.Now()
    log.Println("  END:", s, "ElapsedTime in seconds:", endTime.Sub(startTime))
}

Now you can log any function by just adding this one liner at the top of the function:

func someFunction() {
    defer un(trace("SOME_ARBITRARY_STRING_SO_YOU_CAN_KEEP_TRACK"))

    //do a bunch of stuff here...
}

As you can see trace is called at the beginning of the function while un is deferred to the end.

Again, I can't take credit for this but it's useful for quick and dirty. Also, if you are doing anything more substantial Go has bench-marking and testing tools built-in. You will want to take advantage of those for more accurate and detailed analysis of your code.

Thanks,

-Ralph