介绍
- 函数的运行时间的长短是衡量这个函数性能的重要指标,特别是在对比和基准测试里。
- 要得到函数的运行时间,最简单的办法就是在函数执行之前设置一个起始时间,并在函数运行结束时获取从起始时间到现在的时间间隔,这个时间间隔就是函数的运行时间。
使用
- 在Go语言中我们可以使用
time包中的Since()函数来获取函数的运行时间。 Since()函数返回从 t 到现在经过的时间,等价于time.Now().Sub(t):func Since(t Time) Duration
func test() {start := time.Now() // 获取当前时间sum := 0for i := 0; i < 100000000; i++ {sum++}elapsed1 := time.Since(start) // Sinceelapsed2 := time.Now().Sub(start) // Subfmt.Println("该函数执行完成耗时:", elapsed1, elapsed2)}func main() {test()}
由于计算机 CPU 及一些其他因素的影响,在获取函数运行时间时每次的结果都有些许不同,属于正常现象。
封装
我们可以简单封装一个结构体来实现计算函数执行时间:
type Since struct {Time time.Time}func (s *Since) Start() {s.Time = time.Now()}func (s *Since) Stop(isLog bool) {if sin := time.Since(s.Time); isLog {fmt.Printf("codeing runtime: %d ms", sin)}}
