Skip to content

Instantly share code, notes, and snippets.

@pjambet
Created November 3, 2020 16:36
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 pjambet/5212250aff5fb2cf2ad0de2dd8287dcb to your computer and use it in GitHub Desktop.
Save pjambet/5212250aff5fb2cf2ad0de2dd8287dcb to your computer and use it in GitHub Desktop.
Figuring out if a Float/BigDecimal is an integer
require 'benchmark/ips'
require 'bigdecimal'
Benchmark.ips do |x|
x.report('BD: % 1') { num = BigDecimal(rand(1_000_000_000)); num % 1 == 0 }
x.report('BD: == truncate') { num = BigDecimal(rand(1_000_000_000)); num.truncate == num }
x.report('BD: frac == 0') { num = BigDecimal(rand(1_000_000_000)); num.frac == 0 }
x.report('Float: % 1') { num = rand(1_000_000_000).to_f; num % 1 == 0 }
x.report('Float: == truncate') { num = rand(1_000_000_000).to_f; num.truncate == num }
# x.report('Float: frac == 0') { num = BigDecimal(rand(1_000_000_000)); num.frac == 0 }
end
Warming up --------------------------------------
BD: % 1 21.427k i/100ms
BD: == truncate 26.481k i/100ms
BD: frac == 0 34.369k i/100ms
Float: % 1 269.690k i/100ms
Float: == truncate 292.471k i/100ms
Calculating -------------------------------------
BD: % 1 215.737k (± 4.5%) i/s - 1.093M in 5.075963s
BD: == truncate 262.966k (± 5.0%) i/s - 1.324M in 5.049044s
BD: frac == 0 352.263k (± 4.5%) i/s - 1.787M in 5.084710s
Float: % 1 2.669M (± 9.6%) i/s - 13.215M in 5.028862s
Float: == truncate 3.038M (± 3.7%) i/s - 15.208M in 5.012778s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment