histogram.rb 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/env ruby
  2. # Copyright 2016 gRPC authors.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # Histogram class for use in performance testing and measurement
  16. class Histogram
  17. # Determine the bucket index for a given value
  18. # @param {number} value The value to check
  19. # @return {number} The bucket index
  20. def bucket_for(value)
  21. (Math.log(value)/Math.log(@multiplier)).to_i
  22. end
  23. # Initialize an empty histogram
  24. # @param {number} resolution The resolution of the histogram
  25. # @param {number} max_possible The maximum value for the histogram
  26. def initialize(resolution, max_possible)
  27. @resolution=resolution
  28. @max_possible=max_possible
  29. @sum=0
  30. @sum_of_squares=0
  31. @multiplier=1+resolution
  32. @count=0
  33. @min_seen=max_possible
  34. @max_seen=0
  35. @buckets=Array.new(bucket_for(max_possible)+1, 0)
  36. end
  37. # Add a value to the histogram. This updates all statistics with the new
  38. # value. Those statistics should not be modified except with this function
  39. # @param {number} value The value to add
  40. def add(value)
  41. @sum += value
  42. @sum_of_squares += value * value
  43. @count += 1
  44. if value < @min_seen
  45. @min_seen = value
  46. end
  47. if value > @max_seen
  48. @max_seen = value
  49. end
  50. @buckets[bucket_for(value)] += 1
  51. end
  52. def minimum
  53. @min_seen
  54. end
  55. def maximum
  56. @max_seen
  57. end
  58. def sum
  59. @sum
  60. end
  61. def sum_of_squares
  62. @sum_of_squares
  63. end
  64. def count
  65. @count
  66. end
  67. def contents
  68. @buckets
  69. end
  70. end