class Tryouts::Stats

def dump(msg = "", out=STDERR)

Dump this Stats object with an optional additional message.
def dump(msg = "", out=STDERR)
  out.puts "#{msg}: #{self.to_s}"
end

def initialize(name=:unknown)

def initialize(name=:unknown)
  @name = name
  reset
end

def mean

Calculates and returns the mean for the data passed so far.
def mean
  @sum / @n
end

def reset

Resets the internal counters so you can start sampling again.
def reset
  @sum = 0.0
  @sumsq = 0.0
  @last_time = Time.new
  @n = 0.0
  @min = 0.0
  @max = 0.0
end

def sample(s)

Adds a sampling to the calculations.
def sample(s)
  @sum += s
  @sumsq += s * s
  if @n == 0
    @min = @max = s
  else
    @min = s if @min > s
    @max = s if @max < s
  end
  (@n+=1).to_f
end

def samples; @n; end

def samples; @n; end

def sdev

Calculates the standard deviation of the data so far.
def sdev
  # (sqrt( ((s).sumsq - ( (s).sum * (s).sum / (s).n)) / ((s).n-1) ))
  begin
    Math.sqrt( (@sumsq - ( @sum * @sum / @n)) / (@n-1) ).to_f
  rescue Errno::EDOM
    0.0
  end
end

def tick


t.dump("time")
10000.times { do_stuff(); t.tick }
t = Stats.new("do_stuff")

An example is:

will give you the average time between two activities.
Adds a time delta between now and the last time you called this. This
def tick
  now = Time.now
  sample(now - @last_time)
  @last_time = now
end

def to_s

Returns a common display (used by dump)
def to_s  
"[#{@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]
end