Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created May 22, 2019 22:28
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 havenwood/2e0985c044be9c5df4327b9c85848669 to your computer and use it in GitHub Desktop.
Save havenwood/2e0985c044be9c5df4327b9c85848669 to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
Benchmark.ips do |ips|
N = 1326767
ips.report('a.join.reverse.to_i') { N.digits.each_slice(3).map { |a| a.join.reverse.to_i } }
ips.report('step(3).map') { (0...N.to_s.size).step(3).map{ |i| (N/10**i) % 1000 } }
ips.report('Math.log10') { N.then { |n| 0.step(by: 3, to: Math.log10(n.abs).floor.succ).map { |i| n / 10 ** i % 1000 } } }
ips.report('|a, b = 0, c = 0|') { N.digits.each_slice(3).map { |a, b = 0, c = 0| a + b * 10 + c * 100 } }
ips.compare!
end
Warming up --------------------------------------
a.join.reverse.to_i 21.720k i/100ms
step(3).map 37.398k i/100ms
Math.log10 32.586k i/100ms
|a, b = 0, c = 0| 49.818k i/100ms
Calculating -------------------------------------
a.join.reverse.to_i 226.055k (± 4.8%) i/s - 1.129M in 5.007341s
step(3).map 467.119k (± 6.4%) i/s - 2.356M in 5.065829s
Math.log10 369.276k (± 7.7%) i/s - 1.857M in 5.062217s
|a, b = 0, c = 0| 675.102k (± 8.6%) i/s - 3.388M in 5.062249s
Comparison:
|a, b = 0, c = 0|: 675101.6 i/s
step(3).map: 467118.9 i/s - 1.45x slower
Math.log10: 369275.6 i/s - 1.83x slower
a.join.reverse.to_i: 226055.1 i/s - 2.99x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment