今天想计算程序的耗时时间,为了方便使用defer来计算函数的总的执行时间。但是很少。后来经过如下实验发下了问题:
logsParam := "[test]"
startTime := time.Now()
defer logs.Warning("%s end-cost Seconds:%vs ", logsParam, time.Since(startTime).Seconds())
time.Sleep(2 * time.Second)
logs.Warning("%s end-cost-2 Seconds:%vs ", logsParam, time.Since(startTime).Seconds())
输出:
2020/08/21 14:55:45.888 [W] [proc.go:203] [test] end-cost-2 Seconds:2.000612215s
2020/08/21 14:55:45.888 [W] [proc.go:203] [test] end-cost Seconds:1.45e-07s
使用以上的defer形式来计算耗时确实有问题。
后来找到原因了:defer 调用的函数参数的值 defer 被定义时就确定了。所以耗时参数在defer定义的那块就确定了,所以耗时就很少了。
计算耗时的方法可以改成这样:
logsParam := "[test]"
startTime := time.Now()
defer func(time1 time.Time) {
logs.Warning("%s end-cost Seconds:%v\n", logsParam, time.Since(time1))
}(startTime)
time.Sleep(2 * time.Second)
logs.Warning("%s end-cost-2 Seconds:%vs ", logsParam, time.Since(startTime).Seconds())
输出:
2020/08/21 15:27:31.594 [W] [proc.go:203] [test] end-cost-2 Seconds:2.000604603s
2020/08/21 15:27:31.594 [W] [main.go:58] [test] end-cost Seconds:2.000729234s
圆满完成~~~
有疑问加站长微信联系(非本文作者)