Created
August 11, 2020 07:52
-
-
Save mithi/a3d09f31e9ae340156fdedcf93e1b742 to your computer and use it in GitHub Desktop.
This file contains hidden or 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' | |
require 'test/unit' | |
include Test::Unit::Assertions | |
# Create values | |
# data: [{id, quantity }, {location_id, quantity }] | |
def test_values | |
data = [] | |
location_count = 1_000 | |
max_quantity = 10_000 | |
data_count = 1_000 | |
data_count.times do | |
data << {id: rand(location_count), quantity: rand(max_quantity)} | |
end | |
data | |
end | |
def count_one_line(data) | |
data.each_with_object({}) do |item, count_hash| | |
count_hash[item[:id]] = (count_hash[item[:id]] || 0) + item[:quantity] | |
end | |
end | |
def count_two_lines(data) | |
data.each_with_object({}) do |item, count_hash| | |
count_hash[item[:id]] = count_hash[item[:id]] || 0 | |
count_hash[item[:id]] += item[:quantity] | |
end | |
end | |
N = 10_000 | |
TEST_VALUES = test_values | |
assert_equal count_one_line(TEST_VALUES), count_two_lines(TEST_VALUES) | |
Benchmark.bm do |benchmark| | |
benchmark.report("count_one_line") do | |
N.times do | |
count_one_line(TEST_VALUES) | |
end | |
end | |
benchmark.report("count_two_lines") do | |
N.times do | |
count_two_lines(TEST_VALUES) | |
end | |
end | |
end | |
=begin | |
$ ruby benchmark-simple.rb | |
user system total real | |
count_one_line 3.074869 0.042140 3.117009 ( 3.120487) | |
count_two_lines 4.255742 0.030403 4.286145 ( 4.290792) | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment