Skip to content

Instantly share code, notes, and snippets.

@jmdeldin
Created October 30, 2012 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmdeldin/3983923 to your computer and use it in GitHub Desktop.
Save jmdeldin/3983923 to your computer and use it in GitHub Desktop.
Benchmark is_num methods
# 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
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment