Skip to content

Instantly share code, notes, and snippets.

@aq2bq
Last active January 23, 2020 06:01
Show Gist options
  • Save aq2bq/ead56faee39dc290775a902a00ae1739 to your computer and use it in GitHub Desktop.
Save aq2bq/ead56faee39dc290775a902a00ae1739 to your computer and use it in GitHub Desktop.
[Benchmark] f(int) returns natural number or zero - ruby
require 'benchmark'
q = 10000000
Benchmark.bm 10 do |r|
r.report "IF" do
f = ->(i){ i < 0 ? 0 : i }
q.times {|i| f.call(i) }
end
r.report "ABS" do
f = ->(i){ (i + i.abs) / 2 }
q.times {|i| f.call(i) }
end
r.report "SQRT" do
f = ->(i){ (i + Math.sqrt(i**2)) / 2 }
q.times {|i| f.call(i) }
end
r.report "MAX" do
f = ->(i){ [i, 0].max }
q.times {|i| f.call(i) }
end
end
# user system total real
# IF 0.961154 0.007204 0.968358 ( 1.005658)
# ABS 1.265680 0.008044 1.273724 ( 1.451812)
# SQRT 2.342693 0.014254 2.356947 ( 2.676153)
# MAX 1.061362 0.009373 1.070735 ( 1.195934)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment