Timing Functions:包装和执行日志的函数;
Timing Functions
When optimizing code, sometimes a quick and dirty time measurement is required as opposed to utilizing profiler tools/frameworks to validate assumptions.
在优化代码时,有时需要快速和肮脏的时间度量,而不是使用探查器工具/框架来验证假设。
Time measurements can be performed by utilizing time package and defer statements.
时间测量可以通过使用时间包和延迟语句来完成。
Implementation
1
2
3
4
5
6
7
8
9
10
11
12package profile
import (
"time"
"log"
)
func Duration(invocation time.Time, name string) {
elapsed := time.Since(invocation)
log.Printf("%s lasted %s", name, elapsed)
}Usage
1
2
3
4
5
6
7
8
9
10
11
12
13
14func 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)
}