Skip to content

Instantly share code, notes, and snippets.

@mbbx6spp
Last active March 29, 2017 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbbx6spp/27740500182e1c334bda26b0fd6d343b to your computer and use it in GitHub Desktop.
Save mbbx6spp/27740500182e1c334bda26b0fd6d343b to your computer and use it in GitHub Desktop.
Silly benchmark to satisfy my burning curiousity.
$ ruby bench/lazy.rb
                                                                                                           user     system      total        real
using Range#lazy                                                                                       0.330000   0.000000   0.330000 (  0.330689)
using Enumerator#yield                                                                                 0.170000   0.000000   0.170000 (  0.177117)
using Fiber#yield                                                                                      0.340000   0.120000   0.460000 (  0.458015)
require 'benchmark'
module LazyLists
SECONDS_IN_A_DAY = 86400
def using_range_lazy(start, n)
r0 = (start..Float::INFINITY)
r0.lazy.map { |x| x + SECONDS_IN_A_DAY }.first(n)
end
def using_enum_yield(start, n)
Enumerator.new do |e|
x = start
while n > 0
e.yield (x + SECONDS_IN_A_DAY)
x = x + 1
n -= 1
end
end.map { |x| x }
end
def using_fibers(start, n)
f = Fiber.new do
x = start
loop do
Fiber.yield x
x = x + SECONDS_IN_A_DAY
end
end
n.times { f.resume }
end
end
Benchmark.bm(100) do |x|
include LazyLists
TIMES = 1_000_000
START = 1
x.report('using Range#lazy') do
using_range_lazy(START, TIMES)
end
x.report('using Enumerator#yield') do
using_enum_yield(START, TIMES)
end
x.report('using Fiber#yield') do
using_fibers(START, TIMES)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment