Skip to content

Instantly share code, notes, and snippets.

@mdub
Created March 21, 2012 02:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdub/2143859 to your computer and use it in GitHub Desktop.
Save mdub/2143859 to your computer and use it in GitHub Desktop.
Ruby lazy enumerable benchmark
$ ruby --version
ruby 2.0.0dev (2012-03-20 trunk 35094) [x86_64-darwin11.3.0]
$ ruby pipeline_bench.rb
IMPLEMENTATION take(10) take(100) take(1000) to_a
conventional (eager) 0.01416 0.01407 0.01422 0.01411
enumerating 0.00003 0.00007 0.00063 0.03140
lazing 0.00004 0.00011 0.00098 0.04759
ruby2 Enumerable#lazy 0.00004 0.00013 0.00112 0.05304
facets Enumerable#defer 0.00005 0.00018 0.00162 0.07108
require 'benchmark'
if defined?(Fiber)
require "lazing"
module Enumerable
alias :lazing_select :selecting
alias :lazing_collect :collecting
end
end
require "enumerating"
require 'facets'
array = (1..100000).to_a
# Test scenario:
# - filter out even numbers
# - square them
# - grab the first thousand
printf "%-30s", "IMPLEMENTATION"
printf "%12s", "take(10)"
printf "%12s", "take(100)"
printf "%12s", "take(1000)"
printf "%12s", "to_a"
puts ""
def measure(&block)
begin
printf "%12.5f", Benchmark.realtime(&block)
rescue
printf "%12s", "n/a"
end
end
def benchmark(description, control_result = nil)
result = nil
printf "%-30s", description
measure { yield.take(10).to_a }
measure { yield.take(100).to_a }
measure { result = yield.take(1000).to_a }
measure { yield.to_a }
puts ""
unless control_result.nil? || result == control_result
raise "unexpected result from '#{description}'"
end
result
end
@control = benchmark "conventional (eager)" do
array.select { |x| x.even? }.collect { |x| x*x }
end
benchmark "enumerating", @control do
array.selecting { |x| x.even? }.collecting { |x| x*x }
end
if defined?(Fiber)
benchmark "lazing", @control do
array.lazing_select { |x| x.even? }.lazing_collect { |x| x*x }
end
end
if array.respond_to?(:lazy)
benchmark "ruby2 Enumerable#lazy", @control do
array.lazy.select { |x| x.even? }.lazy.collect { |x| x*x }
end
end
benchmark "facets Enumerable#defer", @control do
array.defer.select { |x| x.even? }.collect { |x| x*x }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment