Skip to content

Instantly share code, notes, and snippets.

@hoxworth
Created April 29, 2011 19:31
Show Gist options
  • Save hoxworth/948876 to your computer and use it in GitHub Desktop.
Save hoxworth/948876 to your computer and use it in GitHub Desktop.
Performance testing really stupid integer counting in Ruby
require 'time'
ITERATIONS = 1000000
rows = [[5,25,2005,1,0,143,2]]
def max_ugly(rows)
max = 1
divvy = 10
rows.each do |row|
while true do
if row[1].to_i / divvy > 0
max = max + 1
divvy = divvy * 10
else
break
end
end
end
max
end
def max_elegant(rows)
rows.collect { |row| row[1].to_s }.map(&:length).max
end
s = Time.now
1.upto(ITERATIONS) {
max_ugly(rows)
}
e = Time.now
ugly_time = e - s
s = Time.now
1.upto(ITERATIONS) {
max_elegant(rows)
}
e = Time.now
elegant_time = e - s
puts "Ugly: #{ugly_time.to_f} seconds"
puts "Elegant: #{elegant_time.to_f} seconds"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment