Skip to content
eregon edited this page Jul 6, 2012 · 8 revisions

There are two kind of benchmarks:

  • counting iterations: for a fast single operation
  • time for a given n: for an operation depending on the size of the given input

Here are some ideas for the API:

Prefer.session do |b|
  b.iterations 'File.stat' do
    File.stat(Dir.tmpdir)
  end

  b.bench 'Array#sort' do |n|
    ary = Array.new(n) { rand(n) }

    b.measure do
      ary.sort
    end
  end
end

With another level of nesting, to separate benchmark code and metadata:

Perfer.session "Array#sort" do |s|
  s.bench "Array#sort" do |b|
    b.description "Sort an Array of n random integer"
    b.bench_code do |n|
      ary = Array.new(n) { rand(n) }

      b.measure do # should not be b here ideally
        ary.sort
      end
    end
  end
end

With the metadata before the #bench block:

Perfer.session "Array#sort" do |s|
  s.description "Sort an Array of n random integer"
  s.tags Array, :sorting
  s.bench "Array#sort" do |b|
    b.bench_code do |n|
      ary = Array.new(n) { rand(n) }

      b.measure do
        ary.sort
      end
    end
  end
end

And the metadata grouped in an instance-eval configuration block:

Perfer.session "Array#sort" do |s|
  s.metadata do
    description "Sort an Array of n random integer"
    tags Array, :sorting
    n "the Array size"
  end
  s.bench "Array#sort" do |b|
    b.bench_code do |n|
      ary = Array.new(n) { rand(n) }

      b.measure do
        ary.sort
      end
    end
  end
end

Clone this wiki locally