github.com/loov/hrtime@v1.0.3/README.md (about) 1 # hrtime 2 3 [![GoDoc](https://godoc.org/github.com/loov/hrtime?status.svg)](http://godoc.org/github.com/loov/hrtime) 4 5 Package hrtime implements high-resolution timing functions and benchmarking utilities. 6 7 `hrtime` relies on using the best timing mechanism on a particular system. At the moment, for Windows it is using Performance Counters and on other platforms standard `time.Now` (since it's good enough). 8 9 Package also supports using hardware time stamp counters (TSC). They offer better accuracy and on some platforms correspond to the processor cycles. However, they are not supported on all platforms. 10 11 For example measuring `time.Sleep` on Mac and Windows. 12 13 ## Example 14 ```go 15 package main 16 17 import ( 18 "fmt" 19 "time" 20 21 "github.com/loov/hrtime" 22 ) 23 24 func main() { 25 start := hrtime.Now() 26 time.Sleep(1000 * time.Nanosecond) 27 fmt.Println(hrtime.Since(start)) 28 29 const numberOfExperiments = 4096 30 31 bench := hrtime.NewBenchmark(numberOfExperiments) 32 for bench.Next() { 33 time.Sleep(1000 * time.Nanosecond) 34 } 35 fmt.Println(bench.Histogram(10)) 36 } 37 ``` 38 39 Output on Mac: 40 41 ``` 42 12µs 43 avg 14.5µs; min 2µs; p50 12µs; max 74µs; 44 p90 22µs; p99 44µs; p999 69µs; p9999 74µs; 45 2µs [ 229] ██▌ 46 10µs [3239] ████████████████████████████████████████ 47 20µs [ 483] ██████ 48 30µs [ 80] █ 49 40µs [ 39] ▌ 50 50µs [ 17] ▌ 51 60µs [ 6] 52 70µs [ 3] 53 80µs [ 0] 54 90µs [ 0] 55 ``` 56 57 Output on Windows: 58 59 ``` 60 1.5155ms 61 avg 1.49ms; min 576µs; p50 1.17ms; max 2.47ms; 62 p90 2.02ms; p99 2.3ms; p999 2.37ms; p9999 2.47ms; 63 577µs [ 1] 64 600µs [ 57] █▌ 65 800µs [ 599] █████████████████ 66 1ms [1399] ████████████████████████████████████████ 67 1.2ms [ 35] █ 68 1.4ms [ 7] 69 1.6ms [ 91] ██▌ 70 1.8ms [ 995] ████████████████████████████ 71 2ms [ 778] ██████████████████████ 72 2.2ms [ 134] ███▌ 73 ``` 74 75 _A full explanation why it outputs this is out of the scope of this document. However, all sleep instructions have a specified granularity and `time.Sleep` actual sleeping time is `requested time ± sleep granularity`. There are also other explanations to that behavior._ 76 77 ## Benchmarking 78 79 `hrtime/hrtesting` can be used to supplement existing benchmarks with more details: 80 81 ```go 82 package hrtesting_test 83 84 import ( 85 "fmt" 86 "runtime" 87 "testing" 88 89 "github.com/loov/hrtime/hrtesting" 90 ) 91 92 func BenchmarkReport(b *testing.B) { 93 bench := hrtesting.NewBenchmark(b) 94 defer bench.Report() 95 96 for bench.Next() { 97 r := fmt.Sprintf("hello, world %d", 123) 98 runtime.KeepAlive(r) 99 } 100 } 101 ```