defer语句将函数的执行推迟到周围的函数返回之前。 但是,如果我尝试打印执行以下功能所花费的时间,它将始终打印0。
func sum() {
start := time.Now()
//expecting to print non zero value but always gets 0
defer fmt.Println(time.Now().Sub(start))
sum := 0
for i := 1; i < 101; i++ {
sum += i
}
time.Sleep(1 * time.Second)
fmt.Println(sum)
}
答案 0 :(得分:8)
延迟函数的参数在延迟函数的点进行评估。将代码更改为以下代码,以评估期望的经过时间:
defer func() { fmt.Println(time.Now().Sub(start)) }()
此处使用的计时逻辑可以放在可重用的函数中:
// timer returns a function that logs message and the elapsed time from
// the call to timer and the returned function. The returned function is
// intended to be used in a defer statement:
// defer timer("sum")()
func timer(message string) func() {
start := time.Now()
return func() { fmt.Println(message, time.Since(start)) }
}
func sum() {
defer timer("sum")()
sum := 0
for i := 1; i < 101; i++ {
sum += i
}
time.Sleep(1 * time.Second)
fmt.Println(sum)
}