report.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. // Copyright 2014 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // the file is borrowed from github.com/rakyll/boom/boomer/print.go
  15. package report
  16. import (
  17. "fmt"
  18. "math"
  19. "sort"
  20. "strings"
  21. "time"
  22. )
  23. const (
  24. barChar = "∎"
  25. )
  26. // Result describes the timings for an operation.
  27. type Result struct {
  28. Start time.Time
  29. End time.Time
  30. Err error
  31. }
  32. func (res *Result) Duration() time.Duration { return res.End.Sub(res.Start) }
  33. type report struct {
  34. results chan Result
  35. precision string
  36. avgTotal float64
  37. fastest float64
  38. slowest float64
  39. average float64
  40. stddev float64
  41. rps float64
  42. total time.Duration
  43. errorDist map[string]int
  44. lats []float64
  45. sps *secondPoints
  46. }
  47. // Stats exposes results raw data.
  48. type Stats struct {
  49. AvgTotal float64
  50. Fastest float64
  51. Slowest float64
  52. Average float64
  53. Stddev float64
  54. RPS float64
  55. Total time.Duration
  56. ErrorDist map[string]int
  57. Lats []float64
  58. TimeSeries TimeSeries
  59. }
  60. // Report processes a result stream until it is closed, then produces a
  61. // string with information about the consumed result data.
  62. type Report interface {
  63. Results() chan<- Result
  64. // Run returns results in print-friendly format.
  65. Run() <-chan string
  66. // Stats returns results in raw data.
  67. Stats() <-chan Stats
  68. }
  69. func NewReport(precision string) Report {
  70. return &report{
  71. results: make(chan Result, 16),
  72. precision: precision,
  73. errorDist: make(map[string]int),
  74. }
  75. }
  76. func NewReportSample(precision string) Report {
  77. r := NewReport(precision).(*report)
  78. r.sps = newSecondPoints()
  79. return r
  80. }
  81. func (r *report) Results() chan<- Result { return r.results }
  82. func (r *report) Run() <-chan string {
  83. donec := make(chan string, 1)
  84. go func() {
  85. defer close(donec)
  86. r.processResults()
  87. donec <- r.String()
  88. }()
  89. return donec
  90. }
  91. func (r *report) Stats() <-chan Stats {
  92. donec := make(chan Stats, 1)
  93. go func() {
  94. defer close(donec)
  95. r.processResults()
  96. donec <- Stats{
  97. AvgTotal: r.avgTotal,
  98. Fastest: r.fastest,
  99. Slowest: r.slowest,
  100. Average: r.average,
  101. Stddev: r.stddev,
  102. RPS: r.rps,
  103. Total: r.total,
  104. ErrorDist: copyMap(r.errorDist),
  105. Lats: copyFloats(r.lats),
  106. TimeSeries: r.sps.getTimeSeries(),
  107. }
  108. }()
  109. return donec
  110. }
  111. func copyMap(m map[string]int) (c map[string]int) {
  112. c = make(map[string]int, len(m))
  113. for k, v := range m {
  114. c[k] = v
  115. }
  116. return
  117. }
  118. func copyFloats(s []float64) (c []float64) {
  119. c = make([]float64, len(s))
  120. copy(c, s)
  121. return
  122. }
  123. func (r *report) String() (s string) {
  124. if len(r.lats) > 0 {
  125. s += fmt.Sprintf("\nSummary:\n")
  126. s += fmt.Sprintf(" Total:\t%s.\n", r.sec2str(r.total.Seconds()))
  127. s += fmt.Sprintf(" Slowest:\t%s.\n", r.sec2str(r.slowest))
  128. s += fmt.Sprintf(" Fastest:\t%s.\n", r.sec2str(r.fastest))
  129. s += fmt.Sprintf(" Average:\t%s.\n", r.sec2str(r.average))
  130. s += fmt.Sprintf(" Stddev:\t%s.\n", r.sec2str(r.stddev))
  131. s += fmt.Sprintf(" Requests/sec:\t"+r.precision+"\n", r.rps)
  132. s += r.histogram()
  133. s += r.sprintLatencies()
  134. if r.sps != nil {
  135. s += fmt.Sprintf("%v\n", r.sps.getTimeSeries())
  136. }
  137. }
  138. if len(r.errorDist) > 0 {
  139. s += r.errors()
  140. }
  141. return s
  142. }
  143. func (r *report) sec2str(sec float64) string { return fmt.Sprintf(r.precision+" secs", sec) }
  144. type reportRate struct{ *report }
  145. func NewReportRate(precision string) Report {
  146. return &reportRate{NewReport(precision).(*report)}
  147. }
  148. func (r *reportRate) String() string {
  149. return fmt.Sprintf(" Requests/sec:\t"+r.precision+"\n", r.rps)
  150. }
  151. func (r *report) processResult(res *Result) {
  152. if res.Err != nil {
  153. r.errorDist[res.Err.Error()]++
  154. return
  155. }
  156. dur := res.Duration()
  157. r.lats = append(r.lats, dur.Seconds())
  158. r.avgTotal += dur.Seconds()
  159. if r.sps != nil {
  160. r.sps.Add(res.Start, dur)
  161. }
  162. }
  163. func (r *report) processResults() {
  164. st := time.Now()
  165. for res := range r.results {
  166. r.processResult(&res)
  167. }
  168. r.total = time.Since(st)
  169. r.rps = float64(len(r.lats)) / r.total.Seconds()
  170. r.average = r.avgTotal / float64(len(r.lats))
  171. for i := range r.lats {
  172. dev := r.lats[i] - r.average
  173. r.stddev += dev * dev
  174. }
  175. r.stddev = math.Sqrt(r.stddev / float64(len(r.lats)))
  176. sort.Float64s(r.lats)
  177. if len(r.lats) > 0 {
  178. r.fastest = r.lats[0]
  179. r.slowest = r.lats[len(r.lats)-1]
  180. }
  181. }
  182. var pctls = []float64{10, 25, 50, 75, 90, 95, 99, 99.9}
  183. // Percentiles returns percentile distribution of float64 slice.
  184. func Percentiles(nums []float64) (pcs []float64, data []float64) {
  185. return pctls, percentiles(nums)
  186. }
  187. func percentiles(nums []float64) (data []float64) {
  188. data = make([]float64, len(pctls))
  189. j := 0
  190. n := len(nums)
  191. for i := 0; i < n && j < len(pctls); i++ {
  192. current := float64(i) * 100.0 / float64(n)
  193. if current >= pctls[j] {
  194. data[j] = nums[i]
  195. j++
  196. }
  197. }
  198. return
  199. }
  200. func (r *report) sprintLatencies() string {
  201. data := percentiles(r.lats)
  202. s := fmt.Sprintf("\nLatency distribution:\n")
  203. for i := 0; i < len(pctls); i++ {
  204. if data[i] > 0 {
  205. s += fmt.Sprintf(" %v%% in %s.\n", pctls[i], r.sec2str(data[i]))
  206. }
  207. }
  208. return s
  209. }
  210. func (r *report) histogram() string {
  211. bc := 10
  212. buckets := make([]float64, bc+1)
  213. counts := make([]int, bc+1)
  214. bs := (r.slowest - r.fastest) / float64(bc)
  215. for i := 0; i < bc; i++ {
  216. buckets[i] = r.fastest + bs*float64(i)
  217. }
  218. buckets[bc] = r.slowest
  219. var bi int
  220. var max int
  221. for i := 0; i < len(r.lats); {
  222. if r.lats[i] <= buckets[bi] {
  223. i++
  224. counts[bi]++
  225. if max < counts[bi] {
  226. max = counts[bi]
  227. }
  228. } else if bi < len(buckets)-1 {
  229. bi++
  230. }
  231. }
  232. s := fmt.Sprintf("\nResponse time histogram:\n")
  233. for i := 0; i < len(buckets); i++ {
  234. // Normalize bar lengths.
  235. var barLen int
  236. if max > 0 {
  237. barLen = counts[i] * 40 / max
  238. }
  239. s += fmt.Sprintf(" "+r.precision+" [%v]\t|%v\n", buckets[i], counts[i], strings.Repeat(barChar, barLen))
  240. }
  241. return s
  242. }
  243. func (r *report) errors() string {
  244. s := fmt.Sprintf("\nError distribution:\n")
  245. for err, num := range r.errorDist {
  246. s += fmt.Sprintf(" [%d]\t%s\n", num, err)
  247. }
  248. return s
  249. }