i want to know how long it takes to do some stuff. I've got some code like this:
def count_stuff(list)
list.inject([]) do |results, item|
results << get_results_from_something_else(values)
end.flatten.uniq
end
def get_results_from_something_else(item)
item.inject([]) do |results, item_value|
results << do_database_work(item_value)
end
end
So, these seems like a massive anti-pattern. This is basically a double inject, and some of the objects we're working with could contain tens of thousands of items. It seems like running this could cause a lot of memory consumption.
So, we're going to see exactly how expensive this operation is.
This code should be simple enough that you can copy-paste into your own editor, and get these results. Lets go!
This is making use of the Benchmark API
require 'benchmark'
run_quantity = 500000
Benchmark.bm do |bm|
# using join
bm.report do
run_quantity.times do
["the", "current", "time", "is", Time.now].join(" ")
end
end
bm.report do
# using string interpolation
run_quantity.times do
"the current time is #{Time.now}"
end
end
end
Run the file, and you'll get something like this:
user system total real
1.900000 0.090000 1.990000 ( 2.285985)
1.520000 0.080000 1.600000 ( 2.473372)
I borrowed the above example from dzone: "How do I Benchmark Ruby Code"
Here's my current work:
require 'benchmark'
run_quantity = 500
numbers = Array.new(100) { rand(1...10000) }
p numbers
Benchmark.bmbm(20) do |bm|
# using join
bm.report('single inject') do
run_quantity.times do
numbers.inject([]) do |results, num|
results << num if num % 2 == 0
results
end.sort
end
end
end