Skip to content

Instantly share code, notes, and snippets.

@biti
Created July 14, 2011 07:54
Show Gist options
  • Save biti/1082074 to your computer and use it in GitHub Desktop.
Save biti/1082074 to your computer and use it in GitHub Desktop.
测试inject叠加
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