finish time profiles patterns

This commit is contained in:
Edward 2020-04-28 22:16:13 +08:00
parent 43071d30c1
commit 5cda2990a0
6 changed files with 67 additions and 0 deletions

View File

@ -44,6 +44,11 @@ Go常用的、面向工程化和最佳实践的模式套路包含常见的23
+ [访问者模式(Visitor)](./behavior/23_visitor) + [访问者模式(Visitor)](./behavior/23_visitor)
+ [闭包选项模式(Function Option)](./behavior/26_option) + [闭包选项模式(Function Option)](./behavior/26_option)
## Go More
+ [发布订阅模式(Pub-Sub)](./gomore/messages)
+ [时差模式(Time Profile)](./gomore/profiles)
## 参考资料(Design patters Articles) ## 参考资料(Design patters Articles)
[GO模式文档](https://github.com/nynicg/go-patterns) [GO模式文档](https://github.com/nynicg/go-patterns)

17
gomore/profiles/README.md Normal file
View File

@ -0,0 +1,17 @@
# 时间差模式
算是一个技巧:
`defer`后面跟的函数参数会被第一时间计算并存储在函数计算过程本地
//当函数在被调用时会利用前面已经存储的值进行计算
```go
func YourMainFunction(input SomeType) error {
defer YourFunc(time.Now(), ....) //一定要放在函数的第一行或者你想要计算时差的代码的前面.
//其他代码..
}
```

View File

@ -0,0 +1,45 @@
package profile
import (
"log"
"math/big"
"time"
"testing"
)
func TestBigintProfile(t *testing.T) {
bigint := big.NewInt(14468)
BigIntFactorial(bigint)
bigint = big.NewInt(24566)
BigIntFactorial(bigint)
}
//Duration for time differ
func Duration(invocation time.Time, name string) {
elapsed := time.Since(invocation)
log.Printf("%s lasted %s", name, elapsed)
}
//BigIntFactorial ...
func BigIntFactorial(input *big.Int) *big.Int {
//关键点是这一句.
defer Duration(time.Now(), "IntFactorial")
x := input
y := big.NewInt(1)
for one := big.NewInt(1); x.Sign() > 0; x.Sub(x, one) {
y.Mul(y, x)
}
return x.Set(y)
}