Skip to content

Instantly share code, notes, and snippets.

@kjlape
Created December 19, 2018 18:46
Show Gist options
  • Select an option

  • Save kjlape/a23ba9fe47373a5cac7fd02bade81832 to your computer and use it in GitHub Desktop.

Select an option

Save kjlape/a23ba9fe47373a5cac7fd02bade81832 to your computer and use it in GitHub Desktop.
Quick n' dirty benchmarking + asserting in ruby scripts
require "benchmark"
require "test/unit/assertions"
extend Test::Unit::Assertions
text = <<END
here's some
text for
you
yeah
💩
END
def method_1(text)
text.strip.split("\n").first.strip
end
def method_2(text)
text.strip.split("\n", 2).first.strip
end
def method_3(text)
first, second = text.strip.split("\n", 2).map(&:strip)
first
end
def method_4(text)
text[/^\n*(.*)\n/, 1]
end
assert_equal "here's some", method_1(text)
assert_equal "here's some", method_2(text)
assert_equal "here's some", method_3(text)
assert_equal "here's some", method_4(text)
n = 1_000_000
Benchmark.bm do |group|
group.report { n.times { method_1(text) } }
group.report { n.times { method_2(text) } }
group.report { n.times { method_3(text) } }
group.report { n.times { method_4(text) } }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment