Created
November 12, 2020 07:08
-
-
Save okuramasafumi/d71a815ace8798704d7870f45605741b to your computer and use it in GitHub Desktop.
Ruby sum benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
huge_array = (1..10000000).to_a | |
Benchmark.bmbm do |x| | |
puts "Adding all numbers" | |
x.report(:sum) { huge_array.sum } | |
x.report(:plus_equal) { sum = 0; huge_array.each {|i| sum += i }; sum} | |
x.report(:inject) { huge_array.inject(:+) } | |
x.report(:inject_block) { huge_array.inject(0) {|memo, i| memo + i} } | |
end | |
Benchmark.bmbm do |x| | |
puts "Adding only even numbers" | |
x.report(:sum) { huge_array.sum {|i| i.even? ? i : 0} } | |
x.report(:plus_equal) { sum = 0; huge_array.each {|i| sum += i if i.even? }; sum} | |
x.report(:inject) { huge_array.inject(0) {|memo, i| i.even? ? memo + i : memo} } | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Adding all numbers | |
Rehearsal ------------------------------------------------ | |
sum 0.025731 0.000095 0.025826 ( 0.025985) | |
plus_equal 0.484651 0.003383 0.488034 ( 0.504850) | |
inject 0.021083 0.000081 0.021164 ( 0.021441) | |
inject_block 0.585306 0.002565 0.587871 ( 0.602357) | |
--------------------------------------- total: 1.122895sec | |
user system total real | |
sum 0.024194 0.000061 0.024255 ( 0.024360) | |
plus_equal 0.460036 0.001802 0.461838 ( 0.470530) | |
inject 0.023195 0.000122 0.023317 ( 0.023391) | |
inject_block 0.621789 0.002185 0.623974 ( 0.635282) | |
Adding only even numbers | |
Rehearsal ---------------------------------------------- | |
sum 0.672182 0.004191 0.676373 ( 0.701799) | |
plus_equal 0.695669 0.005810 0.701479 ( 0.721717) | |
inject 0.992774 0.008890 1.001664 ( 1.064697) | |
------------------------------------- total: 2.379516sec | |
user system total real | |
sum 0.756707 0.005589 0.762296 ( 0.801659) | |
plus_equal 0.705938 0.003404 0.709342 ( 0.725457) | |
inject 0.839872 0.006637 0.846509 ( 0.874628) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment