Skip to content

Instantly share code, notes, and snippets.

@ms-ati
Created November 20, 2017 18:00
Show Gist options
  • Save ms-ati/da6efb18e8c17123c0c009bdc660f860 to your computer and use it in GitHub Desktop.
Save ms-ati/da6efb18e8c17123c0c009bdc660f860 to your computer and use it in GitHub Desktop.
Benchmark "sigfigs" parameter to BigDecimal constructor given a Float
require "benchmark/ips"
require "bigdecimal"
FLOATS = [1.35, 2.35, 3.35, 4.35, 5.35, 6.35, 7.35].freeze
STRINGS = ["1.4", "2.4", "3.4", "4.4", "5.4", "6.4", "7.4"].freeze
FULL = BigDecimal.double_fig
PART = 3
def full_precision
FLOATS.map { |f| BigDecimal.new(f, FULL).round(1).to_f.to_s }
end
def part_precision
FLOATS.map { |f| BigDecimal.new(f, PART).round(1).to_f.to_s }
end
raise "Rounding failure on full precision" unless full_precision == STRINGS
raise "Rounding failure on part precision" unless part_precision == STRINGS
Benchmark.ips do |x|
x.report('BigDecimal.new(f, BigDecimal.double_figs)') { full_precision }
x.report('BigDecimal.new(f, 3 )') { part_precision }
x.compare!
end
$ ruby bench_bigdecimal_from_float.rb
Warming up --------------------------------------
BigDecimal.new(f, BigDecimal.double_figs)
2.577k i/100ms
BigDecimal.new(f, 3 )
2.663k i/100ms
Calculating -------------------------------------
BigDecimal.new(f, BigDecimal.double_figs)
25.596k (± 4.6%) i/s - 128.850k in 5.045449s
BigDecimal.new(f, 3 )
25.137k (± 7.3%) i/s - 125.161k in 5.007108s
Comparison:
BigDecimal.new(f, BigDecimal.double_figs): 25595.8 i/s
BigDecimal.new(f, 3 ): 25137.0 i/s - same-ish: difference falls within error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment