Skip to content

Instantly share code, notes, and snippets.

@pochmann
Last active December 23, 2017 23:37
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 pochmann/0cee969252f3405a082797f8746be8f4 to your computer and use it in GitHub Desktop.
Save pochmann/0cee969252f3405a082797f8746be8f4 to your computer and use it in GitHub Desktop.
# See https://stackoverflow.com/q/47953598/1672429 for discussion
# and sources.
#
# Rehearsal -------------------------------------------------------
# to_s.length 0.297000 0.015000 0.312000 ( 0.316113)
# digits.length 17.562000 0.016000 17.578000 ( 17.597551)
# laborious 3.485000 0.000000 3.485000 ( 3.495671)
# BigDecimal#exponent 0.046000 0.000000 0.046000 ( 0.041986)
# < 10**999 0.032000 0.000000 0.032000 ( 0.027199)
# --------------------------------------------- total: 21.453000sec
#
# user system total real
# to_s.length 0.297000 0.016000 0.313000 ( 0.305834)
# digits.length 17.640000 0.000000 17.640000 ( 17.694883)
# laborious 3.625000 0.000000 3.625000 ( 3.626703)
# BigDecimal#exponent 0.047000 0.000000 0.047000 ( 0.054947)
# < 10**999 0.015000 0.000000 0.015000 ( 0.025909)
require 'bigdecimal'
require 'benchmark'
Benchmark.bmbm do |x|
@x = x
def report(name, &block)
@x.report(name) {
@n.times(&block)
}
end
@n = 10
report('to_s.length') {
number = 3
a = 1
b = 2
while b.to_s.length < 1000
a, b = b, a + b
number += 1
end
raise "wrong" if number != 4782
}
report('digits.length') {
number = 3
a = 1
b = 2
while b.digits.length < 1000
a, b = b, a + b
number += 1
end
raise "wrong" if number != 4782
}
report('laborious') {
number = 3
a = 1
b = 2
while b.to_s.chars.map(&:to_i).reverse.length < 1000
a, b = b, a + b
number += 1
end
raise "wrong" if number != 4782
}
report('BigDecimal#exponent') {
number = 3
a = BigDecimal.new(1)
b = BigDecimal.new(2)
while b.exponent < 1000
a, b = b, a + b
number += 1
end
raise "wrong" if number != 4782
}
report('< 10**999') {
number = 3
a = 1
b = 2
goal = 10**999
while b < goal
a, b = b, a + b
number += 1
end
raise "wrong" if number != 4782
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment