Timing


原文链接: Timing
// CostTime 采用defer CostTime()()实现无侵入调试
//1. 闭包复制的是原对象指针,这就很容易解释延迟引用现象
func CostTime() func() {
	// x := 100
	// fmt.Printf("2. x (%p) = %d\n", &x, x) //x (0x2101ef018) = 100
	start := time.Now()
	return func() {
		fmt.Println("CostTime:", time.Since(start))
		// fmt.Printf("1. x (%p) = %d\n", &x, x) //x (0x2101ef018) = 100
	}
}


实现2

package profile

import (
    "time"
    "log"
)

func Duration(invocation time.Time, name string) {
    elapsed := time.Since(invocation)

    log.Printf("%s lasted %s", name, elapsed)
}

// Usage

func BigIntFactorial(x big.Int) *big.Int {
    // Arguments to a defer statement is immediately evaluated and stored.
    // The deferred function receives the pre-evaluated values when its invoked.
    defer profile.Duration(time.Now(), "IntFactorial")

    y := big.NewInt(1)
    for one := big.NewInt(1); x.Sign() > 0; x.Sub(x, one) {
        y.Mul(y, x)
    }

    return x.Set(y)
}
`