Created
July 14, 2011 07:54
-
-
Save biti/1082074 to your computer and use it in GitHub Desktop.
测试inject叠加
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
def benchmark(test_name) | |
start = Time.now | |
10000.times do | |
yield | |
end | |
seconds = Time.now - start | |
puts "%s time(s): %s" % [test_name, seconds] | |
end | |
arr = [] | |
10.times do |i| | |
arr << {:a => i, :b => i*2} | |
end | |
benchmark 'Test inject sum' do | |
500.times do | |
arr.inject(0) {|sum, item| sum += item[:b]} | |
end | |
end | |
benchmark 'Test normal sum' do | |
500.times do | |
sum = 0 | |
arr.each {|item| sum += item[:b]} | |
end | |
end | |
# $ruby test.rb | |
# Test inject sum time(s): 37.953957 | |
# Test normal sum time(s): 20.543111 | |
# 可见inject确实较慢 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment