1024programmer Java Is there an efficient way to calculate execution time in golang?

Is there an efficient way to calculate execution time in golang?

I’m looking for the best way to calculate execution time.

func main() {
     start := time.Now()

     time.Sleep(time.Second * 2)

     //something doing here

     elapsed := time.Since(start)
     fmt.Printf("page took %s", elapsed)

The above code works fine.

But when I use templates, I have to write it again for every template function.

Is there an efficient way to calculate execution time, including templates?

1> Cerise Limón..:

If you want to time the entire function, then you can use this deferTo eliminate some duplicate code.

func elapsed(what string) func() {
     start := time.Now()
     return func() {
         fmt.Printf("%s took %v\n", what, time.Since(start))

 func main() {
     defer elapsed("page")() // <-- The trailing () is the deferred call
     time.Sleep(time.Second * 2)

Playground example

2> Mohsin..:

The solution provided by Cerise is perfect.

Also, if you don’t want to pass the function name explicitly, you can accomplish it like this:

func SomeFunction(list *[]string) {
     defer TimeTrack(time.Now())
     // Do whatever you want.

 func TimeTrack(start time.Time) {
     elapsed := time.Since(start)

     // Skip this function, and fetch the PC and file for its parent.
     pc, _, _, _ := runtime.Caller(1)

     // Retrieve a function object this functions parent.
     funcObj := runtime.FuncForPC(pc)

     // Regex to extract just the function name (and not the module path).
     runtimeFunc := regexp.MustCompile(`^.*\.(.*)$`)
     name := runtimeFunc.ReplaceAllString(funcObj.Name(), "$1")

     log.Println(fmt.Sprintf("%s took %s", name, elapsed))

As a result, you will get:

SomeFunction took 15.483µs

For more information, see this article: Go Function Tracing

Share knowledge.:)

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/768482

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us


Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top