简单方式
package main
import(
"fmt"
"time"
)
func main(){
defer timeCost(time.Now())
fmt.Println("start program")
time.Sleep(5*time.Second)
fmt.Println("finish program")
}
func timeCost(start time.Time){
terminal:=time.Since(start)
fmt.Println(terminal)
}
更优雅的方式
func timeCost() func() {
start := time.Now()
return func() {
tc:=time.Since(start)
fmt.Printf("time cost = %v\n", tc)
}
}
调用方式:
defer timeCost()()