OSDN Git Service

f6cf5ab6c39d1956fd9a388064a3efb00f9b6291
[redminele/redminele.git] / ruby / lib / ruby / gems / 1.8 / gems / mongrel-1.1.5-x86-mswin32-60 / lib / mongrel / stats.rb
1 # Copyright (c) 2005 Zed A. Shaw 
2 # You can redistribute it and/or modify it under the same terms as Ruby.
3 #
4 # Additional work donated by contributors.  See http://mongrel.rubyforge.org/attributions.html 
5 # for more information.
6
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.
12 #
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.
15 module Mongrel
16   class Stats
17     attr_reader :sum, :sumsq, :n, :min, :max
18
19     def initialize(name)
20       @name = name
21       reset
22     end
23
24     # Resets the internal counters so you can start sampling again.
25     def reset
26       @sum = 0.0
27       @sumsq = 0.0
28       @last_time = Time.new
29       @n = 0.0
30       @min = 0.0
31       @max = 0.0
32     end
33
34     # Adds a sampling to the calculations.
35     def sample(s)
36       @sum += s
37       @sumsq += s * s
38       if @n == 0
39         @min = @max = s
40       else
41         @min = s if @min > s
42         @max = s if @max < s
43       end
44       @n+=1
45     end
46
47     # Dump this Stats object with an optional additional message.
48     def dump(msg = "", out=STDERR)
49       out.puts "#{msg}: #{self.to_s}"
50     end
51
52     # Returns a common display (used by dump)
53     def to_s  
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]
55     end
56
57
58     # Calculates and returns the mean for the data passed so far.
59     def mean
60       @sum / @n
61     end
62
63     # Calculates the standard deviation of the data so far.
64     def sd
65       # (sqrt( ((s).sumsq - ( (s).sum * (s).sum / (s).n)) / ((s).n-1) ))
66       begin
67         return Math.sqrt( (@sumsq - ( @sum * @sum / @n)) / (@n-1) )
68       rescue Errno::EDOM
69         return 0.0
70       end
71     end
72
73
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.
76     # 
77     # An example is:
78     #
79     #  t = Stats.new("do_stuff")
80     #  10000.times { do_stuff(); t.tick }
81     #  t.dump("time")
82     #
83     def tick
84       now = Time.now
85       sample(now - @last_time)
86       @last_time = now
87     end
88   end
89 end