Created
March 22, 2018 01:36
-
-
Save mboeh/bb480d93c71046e23816f2c24c23e3b4 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 "benchmark/memory" | |
N = 10_000_000 | |
nonlazy = ->{ (1..N) .select(&:even?).map{|i| i*2 }.map{|i| i + 1 }.map(&:to_s).map(&:reverse).to_a.join(",").length } | |
lazy = ->{ (1..N).lazy.select(&:even?).map{|i| i*2 }.map{|i| i + 1 }.map(&:to_s).map(&:reverse).to_a.join(",").length } | |
one = ->{ | |
(1..N).each_with_object([]) do |i,a| | |
if i.even? | |
a << ((i*2)+1).to_s.reverse | |
end | |
end.join(",").length | |
} | |
nonlazy.() == lazy.() or fail | |
lazy.() == one.() or fail | |
puts "== CPU ==" | |
Benchmark.bmbm do |x| | |
x.report("nonlazy x#{N}", &nonlazy) | |
x.report("lazy x#{N}", &lazy) | |
x.report("one x#{N}", &one) | |
end | |
puts "== Memory ==" | |
Benchmark.memory do |x| | |
x.report("nonlazy x#{N}", &nonlazy) | |
x.report("lazy x#{N}", &lazy) | |
x.report("one x#{N}", &one) | |
x.compare! | |
end | |
=begin | |
== CPU == | |
Rehearsal ----------------------------------------------------- | |
nonlazy x10000000 3.900000 0.310000 4.210000 ( 4.235131) | |
lazy x10000000 9.330000 0.870000 10.200000 ( 10.258059) | |
------------------------------------------- total: 14.410000sec | |
user system total real | |
nonlazy x10000000 3.700000 2.640000 6.340000 ( 6.347430) | |
lazy x10000000 9.000000 1.220000 10.220000 ( 10.284903) | |
== Memory == | |
Calculating ------------------------------------- | |
nonlazy x10000000 618.909M memsize ( 0.000 retained) | |
10.000M objects ( 0.000 retained) | |
50.000 strings ( 0.000 retained) | |
lazy x10000000 1.459B memsize ( 0.000 retained) | |
35.000M objects ( 0.000 retained) | |
50.000 strings ( 0.000 retained) | |
Comparison: | |
nonlazy x10000000: 618909008 allocated | |
lazy x10000000: 1458914488 allocated - 2.36x more | |
(I implemented the 'one' option later, this is how it turned out:) | |
== CPU == | |
Rehearsal ------------------------------------------------- | |
one x10000000 3.090000 0.160000 3.250000 ( 3.281496) | |
---------------------------------------- total: 3.250000sec | |
user system total real | |
one x10000000 2.570000 0.040000 2.610000 ( 2.628678) | |
== Memory == | |
Calculating ------------------------------------- | |
one x10000000 458.909M memsize ( 0.000 retained) | |
10.000M objects ( 0.000 retained) | |
50.000 strings ( 0.000 retained) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment