public
Created

Benchmark is_num methods

  • Download Gist
bench.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# from http://stackoverflow.com/questions/13149146/ruby-rails-determine-if-variable-is-a-number
require 'benchmark'
 
def is_num_e(num_given)
!!Integer(num_given) rescue false
end
 
def is_num_r(num_given)
num_given =~ /\d+(\.\d+)?/
end
 
Benchmark.bmbm do |x|
x.report("exception w/valid input") { 100_000.times { |i| is_num_e("#{i}") } }
x.report("regexp w/valid input") { 100_000.times { |i| is_num_r("#{i}") } }
 
x.report("exception w/invalid input") { 100_000.times { |i| is_num_e("a#{i}") } }
x.report("regexp w/invalid input") { 100_000.times { |i| is_num_r("a#{i}") } }
end
output.txt
1 2 3 4 5 6 7 8 9 10 11 12
Rehearsal -------------------------------------------------------------
exception w/valid input 0.050000 0.000000 0.050000 ( 0.054714)
regexp w/valid input 0.160000 0.000000 0.160000 ( 0.158725)
exception w/invalid input 1.120000 0.050000 1.170000 ( 1.170184)
regexp w/invalid input 0.170000 0.000000 0.170000 ( 0.170790)
---------------------------------------------------- total: 1.550000sec
 
user system total real
exception w/valid input 0.050000 0.000000 0.050000 ( 0.052318)
regexp w/valid input 0.160000 0.000000 0.160000 ( 0.154336)
exception w/invalid input 1.060000 0.050000 1.110000 ( 1.105803)
regexp w/invalid input 0.170000 0.000000 0.170000 ( 0.171973)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.