Correctly measure time duration in Go

前端 未结 3 1898
有刺的猬
有刺的猬 2020-12-17 08:39

What is the correct way to precisely measure a time duration in Go? Most application just use the standard time package and the following approach:

var start         


        
3条回答
  •  情歌与酒
    2020-12-17 08:53

    For Go 1.8 and before, the correct timing function is not inside the time package, but instead in the runtime package:

    func nanotime() int64
    

    In order to correctly measure execution time, the following procedure should be used:

    var startTime = runtime.nanotime()
    doSomeHardWork()
    var duration = runtime.nanotime() - startTime
    

    Unfortunately, the method itself is not documented very well. It emerged in this issue after a long discussion if it was really neccessary. For Go 1.9 and newer, refer to Kenny Grant's answer.

提交回复
热议问题