Created
October 30, 2012 23:58
-
-
Save jmdeldin/3983923 to your computer and use it in GitHub Desktop.
Benchmark is_num methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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