Last active
December 15, 2015 00:49
-
-
Save shunsugai/5175446 to your computer and use it in GitHub Desktop.
Ruby2.0の新機能、lazyを調査中。
This file contains 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
# Benchmark of Enumerable#lazy. | |
# 'production.log' is a log of Rails application that size is 43.6MB. | |
require 'benchmark' | |
Benchmark.bm do |x| | |
x.report('normal') do | |
100.times do | |
File.open("./production.log") do |f| | |
f.each_line.select { |line| line =~ /RoutingError/ }.first(10) | |
end | |
end | |
end | |
x.report('with lazy') do | |
100.times do | |
File.open("./production.log") do |f| | |
f.each_line.lazy.select { |line| line =~ /RoutingError/ }.first(10) | |
end | |
end | |
end | |
end | |
# user system total real | |
# non lazy 201.990000 18.420000 220.410000 (229.605248) | |
# with lazy 0.140000 0.020000 0.160000 ( 0.169942) | |
# [Finished in 230.0s] | |
# sample.logは各行に1~20までの数字が入っているだけのファイル。 | |
# not lazy | |
File.open("./sample.log") do |f| | |
puts f.each_line.map(&:to_i).select{|x| x % 2 == 0}.first(3) | |
end | |
# map method returns an Array object like following. | |
# [1,2,3,...20] | |
# lazy | |
File.open("./sample.log") do |f| | |
puts f.each_line.lazy.map(&:to_i).select{|x| x % 2 == 0}.first(3) | |
end |
ちなみに似たようなやつを10000万回まわしたら1.9.3だと2時間強かかった。
user system total real
Ruby2.0.0 p-0 with lazy 17.540000 1.390000 18.930000 ( 19.041330)
Ruby1.9.3 p-125 7661.230000 238.900000 7900.130000 (8324.068630)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
るびま
http://jp.rubyist.net/magazine/?0041-200Special-lazy