1 # Copyright (c) 2005 Zed A. Shaw
2 # You can redistribute it and/or modify it under the same terms as Ruby.
4 # Additional work donated by contributors. See http://mongrel.rubyforge.org/attributions.html
5 # for more information.
7 # A very simple little class for doing some basic fast statistics sampling.
8 # You feed it either samples of numeric data you want measured or you call
9 # Stats.tick to get it to add a time delta between the last time you called it.
10 # When you're done either call sum, sumsq, n, min, max, mean or sd to get
11 # the information. The other option is to just call dump and see everything.
13 # It does all of this very fast and doesn't take up any memory since the samples
14 # are not stored but instead all the values are calculated on the fly.
17 attr_reader :sum, :sumsq, :n, :min, :max
24 # Resets the internal counters so you can start sampling again.
34 # Adds a sampling to the calculations.
47 # Dump this Stats object with an optional additional message.
48 def dump(msg = "", out=STDERR)
49 out.puts "#{msg}: #{self.to_s}"
52 # Returns a common display (used by dump)
54 "[#{@name}]: SUM=%0.4f, SUMSQ=%0.4f, N=%0.4f, MEAN=%0.4f, SD=%0.4f, MIN=%0.4f, MAX=%0.4f" % [@sum, @sumsq, @n, mean, sd, @min, @max]
58 # Calculates and returns the mean for the data passed so far.
63 # Calculates the standard deviation of the data so far.
65 # (sqrt( ((s).sumsq - ( (s).sum * (s).sum / (s).n)) / ((s).n-1) ))
67 return Math.sqrt( (@sumsq - ( @sum * @sum / @n)) / (@n-1) )
74 # Adds a time delta between now and the last time you called this. This
75 # will give you the average time between two activities.
79 # t = Stats.new("do_stuff")
80 # 10000.times { do_stuff(); t.tick }
85 sample(now - @last_time)