Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

About this user

« Newer Snippets
Older Snippets »
1 total  XML / RSS feed 

Benchmark methods

Here we define two ways to process chunks of Array elements at a time.

Below we define a benchmarking test using a double run, one as a preliminary run, one as a real test run.

class Array
  def process(method_obj, batch_size = 10, fin = [])
    if (this_batch = self.first(batch_size)).size > 0
      fin.concat method_obj.call(this_batch)
      (self - this_batch).process(method_obj, batch_size, fin)
    else
      return fin
    end
  end
  
  def proc_array(method_obj, batch_size = 2)
    result = []
    self.each_slice(batch_size) do |batch|
      result.concat method_obj.call(batch)
    end
    result
  end
end

def munge(ary)
  ary.collect { |e| e.+ 10 }
end

my_meth = method(:munge)

BIGARY = Array.new(100) {|i| i}

require 'benchmark'
include Benchmark

bmbm(2) do |test|
  test.report("recursive") do
    10000.times {BIGARY.process(my_meth, 2)}
  end
  test.report("block") do
    10000.times {BIGARY.proc_array(my_meth)}
  end
end
« Newer Snippets
Older Snippets »
1 total  XML / RSS feed