如何计算Go并发函数的执行时间

huangapple go评论69阅读模式
英文:

How to calculate execution time of Go concurrent function

问题

你可以使用time.Now()函数来计算并发函数(goroutine)的执行时间。但是,由于CPU在不同的goroutine之间共享,并且goroutine的执行顺序是不确定的,所以你可能无法得到准确的执行时间。如果你只是想大致估计执行时间,那么你的代码是可以使用的。但如果你需要更精确的执行时间,你可能需要使用其他方法,比如使用sync.WaitGroup来等待所有的goroutine执行完毕,然后再计算执行时间。

英文:

I want to calculate execution time of concurrent function( go routine) in golang.

I am using below code, but I think it's giving me wrong time. As we know cpu is shared among go routines and go routines shuffle for execution as one routine can't occupy more time on cpu. I think my solution is incorrect. Please suggest right way. If my understanding is incorrect then also correct me.

func timeElapsed() func() {

   start := time.Now()

   return func() {

      timeElapsed := time.Since(start)

      fmt.Println("This function took", timeElapsed, "time")
   }
}

func thisIsGoFunction {

   defer timeElapsed()()

   //Some code which is doing some iterations over map and mutex
}

答案1

得分: 2

这种方法适用于测量同步调用的时间,而不适用于 goroutine。

对于并发函数的执行时间,最好的计算方法是使用带有 cpuprofile 选项的基准测试,该选项会生成可以输入给 pprof 的 CPU 分析文件。

或者直接在代码中包含 pprof,运行负载,然后查看图形,例如火焰图。

英文:

This approach is good for measuring time of synchronous calls not for goroutines.

For concurrent functions execution time can be best calculated by using either benchmark tests with cpuprofile option, which produces cpu profile file that can be fed to pprof.

Or directly including pprof in code, run load, and then see the graph e.g. flame graph

huangapple
  • 本文由 发表于 2023年6月26日 01:40:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76551687.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定