Skip to content

Instantly share code, notes, and snippets.

@tkfm-yamaguchi
Created January 29, 2018 01:19
Show Gist options
  • Save tkfm-yamaguchi/64aa598cf232604201c67ed7b3250fef to your computer and use it in GitHub Desktop.
Save tkfm-yamaguchi/64aa598cf232604201c67ed7b3250fef to your computer and use it in GitHub Desktop.
measure the time to get the sum of digits
require "benchmark"
# Sum of digits
TARGET = 123456789
def sum_by_s
TARGET.to_s.chars.map(&:to_i).sum
end
def sum_by_d
n = TARGET
sum = 0
Math.log10(TARGET).ceil.times do
sum += n % 10
n /= 10
end
sum
end
def sum_by_l
n = TARGET
sum = 0
while n > 0
sum += n % 10
n /= 10
end
sum
end
n = 100000
Benchmark.bm do |x|
x.report { n.times{ sum_by_s } }
x.report { n.times{ sum_by_d } }
x.report { n.times{ sum_by_l } }
end
# =>
# user system total real
# 0.210000 0.000000 0.210000 ( 0.218448)
# 0.090000 0.000000 0.090000 ( 0.090375)
# 0.050000 0.000000 0.050000 ( 0.050930)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment