Skip to content

Instantly share code, notes, and snippets.

@mikecmpbll
Created May 22, 2019 22:41
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 mikecmpbll/a1523af6b84d2cf1553b6b89050740df to your computer and use it in GitHub Desktop.
Save mikecmpbll/a1523af6b84d2cf1553b6b89050740df to your computer and use it in GitHub Desktop.
Ruby 2.5.1 number thingy benchmark
Warming up --------------------------------------
maths 50.286k i/100ms
slice map 34.402k i/100ms
multi map 13.137k i/100ms
original 24.600k i/100ms
gsub 14.685k i/100ms
all maths 55.759k i/100ms
readable 14.009k i/100ms
Calculating -------------------------------------
maths 663.215k (± 2.9%) i/s - 3.319M in 5.008728s
slice map 446.610k (± 1.9%) i/s - 2.236M in 5.008779s
multi map 161.509k (± 2.5%) i/s - 814.494k in 5.046579s
original 310.873k (± 2.8%) i/s - 1.574M in 5.069136s
gsub 190.076k (± 5.6%) i/s - 954.525k in 5.040161s
all maths 596.778k (± 4.5%) i/s - 3.011M in 5.055396s
readable 146.767k (± 5.7%) i/s - 742.477k in 5.074410s
Comparison:
maths: 663215.2 i/s
all maths: 596777.9 i/s - 1.11x slower
slice map: 446610.2 i/s - 1.48x slower
original: 310872.6 i/s - 2.13x slower
gsub: 190075.6 i/s - 3.49x slower
multi map: 161509.3 i/s - 4.11x slower
readable: 146767.2 i/s - 4.52x slower
Benchmark.ips do |x|
N = 1326767
x.report("maths"){ (0...N.to_s.size).step(3).map{ |i| (N/10**i) % 1000 } }
x.report("slice map"){ N.digits.each_slice(3).map { |a, b = 0, c = 0| a + b * 10 + c * 100 } }
x.report("multi map"){ N.digits.each_slice(3).map(&:join).map(&:reverse).map(&:to_i) }
x.report("original"){ N.to_s.reverse.scan(/\d{1,3}/).map(&:reverse).map(&:to_i) }
x.report("gsub"){ N.to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, '\1,').split(",").map(&:to_i).reverse }
x.report("all maths"){ (0..Math.log10(N.abs).floor).step(3).map{ |i| (N/10**i) % 1000 } }
x.report("readable"){ N.digits.each_slice(3).map { |a| a.join.reverse.to_i } }
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment