diff --git a/README.md b/README.md index dd0fc07..9460ea3 100644 --- a/README.md +++ b/README.md @@ -98,7 +98,7 @@ A curated collection of idiomatic design & application patterns for Go language. | Pattern | Description | Status | |:-------:|:----------- |:------:| -| [Timing Functions](/profiling/timing.md) | Wraps a function and logs the execution | ✘ | +| [Timing Functions](/profiling/timing.md) | Wraps a function and logs the execution | ✔ | ## Idioms diff --git a/profiling/timing.md b/profiling/timing.md new file mode 100644 index 0000000..8de3ed1 --- /dev/null +++ b/profiling/timing.md @@ -0,0 +1,38 @@ +# 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 + +```go +package profile + +import ( + "time" + "log" +) + +func Duration(invocation time.Time, name string) { + elapsed := time.Since(invocation) + + log.Printf("%s lasted %s", name, elapsed) +} +``` + +## Usage + +```go +func IntFactorial(x big.Int) *big.Int { + 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) +} +```