Created
September 20, 2010 13:33
-
-
Save manveru/587910 to your computer and use it in GitHub Desktop.
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
require 'benchmark' | |
class Numeric | |
def split_digits_1(base = 10) | |
# head, last = self.divmod(base) | |
head = self / base | |
last = self % base | |
head < base ? [head, last] : head.split_digits_1(base).push(last) | |
end | |
def split_digits_2(base = 10) | |
total, result = self, [] | |
while total > 0 | |
fraction = total % base | |
total /= base | |
result << fraction | |
end | |
result.reverse | |
end | |
def split_digits_3(base = 10) | |
total, result = self, [] | |
while total > 0 | |
fraction = total % base | |
total /= base | |
result.unshift fraction | |
end | |
result | |
end | |
def split_digits_4(base = 10) | |
total, result = self, [] | |
while total > 0 | |
total, fraction = total.divmod(base) | |
result << fraction | |
end | |
result.reverse | |
end | |
end | |
N = 100e100.to_i | |
TIMES = 10_000 | |
p N.split_digits_1 | |
p N.split_digits_2 | |
p N.split_digits_3 | |
p N.split_digits_4 | |
Benchmark.bmbm do |b| | |
b.report '1' do | |
TIMES.times do | |
N.split_digits_1 | |
end | |
end | |
b.report '2' do | |
TIMES.times do | |
N.split_digits_2 | |
end | |
end | |
b.report '3' do | |
TIMES.times do | |
N.split_digits_3 | |
end | |
end | |
b.report '4' do | |
TIMES.times do | |
N.split_digits_3 | |
end | |
end | |
end |
Author
manveru
commented
Sep 20, 2010
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment