英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论