Performance Benchmarking Ruby with MiniTest
A handy feature of MiniTest is the performance benchmarking assertions. Here's an example testing a couple of methods that are constant and linear in time as a function of their inputs:
require 'rubygems'
require 'minitest/benchmark'
require 'minitest/autorun'
class Thing
def constant_time_method(n)
true # O(1)
end
def linear_time_method(n)
n.times { |i| constant_time_method(i) } # O(n)
end
end
class AwesomeTest < MiniTest::Unit::TestCase
def setup
@thing = Thing.new
end
def test_constant_time_method_performance
assert_performance_constant 0.99999 do |n|
@thing.constant_time_method(n)
end
end
def test_linear_time_method_performance
assert_performance_linear 0.9999 do |n|
@thing.linear_time_method(n)
end
end
end
Whilst I wouldn't go nuts with this, it's a nice solution for when you have optimized some code and want to add a check against regressions.
Scope the source and docs for more details.