首页 > 代码库 > golang 之 defer(统计函数执行时间)

golang 之 defer(统计函数执行时间)

 1 package main 2  3 import ( 4     "fmt" 5     "time" 6 ) 7  8 func sum(a ...int) int { 9     defer trace("sum")() // note:不要忘记defer语句后的圆括号,否则本该在进入时执行的操作会在退出时执行,而本该在退出时执行的,永远不会执行10     total := 011     for _, val := range a {12         total += val13     }14     return total15 }16 17 func trace(msg string) func() {18     start := time.Now()19     fmt.Printf("enter %s\n", msg)20     return func() {21         fmt.Printf("exit %s (%s)\n", msg, time.Since(start))22     }23 }24 25 func main() {26     count := sum(3, 5, 9)27     fmt.Printf("%d\n", count)28 }

执行结果:

1 enter sum2 exit sum (194.764µs)3 17

 利用defer修改函数的返回值:

 1 package main 2  3 import ( 4     "fmt" 5     "time" 6 ) 7  8 func sum(a, b int) (result int) { 9     //defer trace("sum")() // note:不要忘记defer语句后的圆括号,否则本该在进入时执行的操作会在退出时执行,而本该在退出时执行的,永远不会执行10     defer func() { result += a }() //被延时执行的匿名函数甚至可以修改函数返回给调用者的返回值11     result = 012     result += a13     result += b14     return result15 }16 17 func trace(msg string) func() {18     start := time.Now()19     fmt.Printf("enter %s\n", msg)20     return func() {21         fmt.Printf("exit %s (%s)\n", msg, time.Since(start))22     }23 }24 25 func main() {26     count := sum(3, 8)27     fmt.Printf("%d\n", count)28 }

执行结果:

1 [root@docker pro]# go run arg.go 2 [root@docker pro]# go run arg.go 3 14

 

golang 之 defer(统计函数执行时间)