SyMind / learning

路漫漫其修远兮,吾将上下而求索。
9 stars 1 forks source link

Go 语言测量函数执行时间 #49

Open SyMind opened 1 year ago

SyMind commented 1 year ago

测量一段代码

start := time.Now()
// Code to measure
duration := time.Since(start)

// Formatted string, such as "2h3m0.5s" or "4.503μs"
fmt.Println(duration)

// Nanoseconds as int64
fmt.Println(duration.Nanoseconds())

测量函数调用

func foo() {
    defer duration(track("foo"))
    // Code to measure
}
func track(msg string) (string, time.Time) {
    return msg, time.Now()
}

func duration(msg string, start time.Time) {
    log.Printf("%v: %v\n", msg, time.Since(start))
}