花费时间在Go中执行功能

A defer statement defers the execution of a function until the surrounding function returns. However, if I try to print the time taken to execute the following function, it always prints 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)
}

Snippet: https://play.golang.org/p/46dxtS5beET

The arguments to the deferred function are evaluated at the point the function is deferred. Change the code the following to evaluate the elapsed time as you expect:

defer func() { fmt.Println(time.Now().Sub(start)) }()

The timing logic used here can be placed in a reusable function:

// 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)
}