本教程操作环境:windows7系统、go 1.18版本、dell g3电脑。
使用time.since计算执行时间
函数的运行时间的长短是衡量这个函数性能的重要指标,特别是在对比和基准测试中,要得到函数的运行时间,最简单的办法就是在函数执行之前设置一个起始时间,并在函数运行结束时获取从起始时间到现在的时间间隔,这个时间间隔就是函数的运行时间。
在go语言中我们可以使用 time 包中的 since() 函数来获取函数的运行时间,go语言官方文档中对 since() 函数的介绍是这样的。
func since(t time) duration
since() 函数返回从 t 到现在经过的时间,等价于time.now().sub(t)。
示例1:使用 since() 函数获取函数的运行时间
package mainimport ( "fmt" "time")func test() { start := time.now() // 获取当前时间 sum := 0 for i := 0; i < 100000000; i++ { sum++ } elapsed := time.since(start) fmt.println("该函数执行完成耗时:", elapsed)}func main() { test()}
运行结果如下所示:
该函数执行完成耗时: 39.8933ms
上面我们提到了 time.now().sub() 的功能类似于 since() 函数,想要使用 time.now().sub() 获取函数的运行时间只需要把我们上面代码的第 14 行简单修改一下就行。
示例2:使用 time.now().sub() 获取函数的运行时间
package mainimport ( "fmt" "time")func test() { start := time.now() // 获取当前时间 sum := 0 for i := 0; i < 100000000; i++ { sum++ } elapsed := time.now().sub(start) fmt.println("该函数执行完成耗时:", elapsed)}func main() { test()}
运行结果如下所示:
该函数执行完成耗时: 36.8769ms
由于计算机 cpu 及一些其他因素的影响,在获取函数运行时间时每次的结果都有些许不同,属于正常现象。
扩展知识:使用time.now().sub()计算时间差
我们只需将time.since()替换成 time.now().sub() 即可,如下:
start := time.now() // 获取当前时间 sum := 0 for i := 0; i < 100000000; i++ { sum++ } elapsed := time.now().sub(start) fmt.println(elapsed)
其实time.since内部调用了sub函数,我们进入time包看,注释的意思是,since返回从t开始经过的时间, time.since 是 time.now().sub(t) 的简写方式,
\src\time\time.go 923:6
// since returns the time elapsed since t.// it is shorthand for time.now().sub(t).func since(t time) duration { var now time if t.wall&hasmonotonic != 0 { // common case optimization: if t has monotonic time, then sub will use only it. now = time{hasmonotonic, runtimenano() - startnano, nil} } else { now = now() } return now.sub(t)}
当我们也可以使用 time.now().sub(start).seconds()获取经过多少秒,hours获取经过的小时数等,对应的也可以简写为time.since(start).seconds()、time.since(start).seconds()等。
【相关推荐:go视频教程、编程教学】
以上就是go语言怎么获取函数执行时间的详细内容。
