Skip to content

Instantly share code, notes, and snippets.

@ucarion
Created January 26, 2014 07:47
Show Gist options
  • Save ucarion/8629784 to your computer and use it in GitHub Desktop.
Save ucarion/8629784 to your computer and use it in GitHub Desktop.
Performance of array-averaging in Ruby vs. C
require 'benchmark'
require 'extension_cord'
def average_reduce(arr)
arr.reduce(:+).to_f / arr.size
end
def average_upto(arr)
sum = 0
0.upto(arr.size - 1) do |n|
sum += arr.at(n)
end
sum.to_f / arr.size
end
def average_each(arr)
sum = 0
arr.each do |val|
sum += val
end
sum.to_f / arr.size
end
def average_while(arr)
sum = 0
i = 0
while i < arr.size
sum += arr.at(i)
i += 1
end
sum.to_f / arr.size
end
array = Array.new(1_000_000) { rand(0..1000) }
ITERATIONS = 100
Benchmark.bm(10) do |b|
b.report("reduce:") { ITERATIONS.times { average_reduce(array) } }
b.report("upto:") { ITERATIONS.times { average_upto(array) } }
b.report("each:") { ITERATIONS.times { average_each(array) } }
b.report("while:") { ITERATIONS.times { average_while(array) } }
b.report("c:") { ITERATIONS.times { ExtensionCord.avg_of_array(array) } }
end
# Output:
# user system total real
# reduce: 5.900000 0.010000 5.910000 ( 5.906489)
# upto: 7.980000 0.000000 7.980000 ( 7.994691)
# each: 5.920000 0.010000 5.930000 ( 5.929237)
# while: 5.660000 0.000000 5.660000 ( 5.661042)
# c: 0.940000 0.000000 0.940000 ( 0.943013)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment