Code Worrier

Teaching myself to RTFM

A Tiny Benchmarking Utility

| Comments

While working on a longer (forthcoming) post, I wrote a little benchmarking utility that I want to share. Here it is:

tiny_timer.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
module TinyTimer
  def self.benchmark(samples=10)

    times = []

    samples.times do
      start = Time.now
      yield
      times << (Time.now - start)
    end

    times.sum / samples.to_f

  end
end

As you can see, this method runs a specified number of trials of a block of code and returns the average time in seconds it took to execute the block. Usage examples:

1
2
3
4
5
6
>> require 'tiny_timer'
=> ["TinyTimer"]
>> TinyTimer.benchmark{ (0..100000).map{rand(10)}.sort }
=> 0.0670641
>> TinyTimer.benchmark(100){ 2**1000000 }
=> 0.00841815

Comments