Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
executable file 59 lines (47 sloc) 1.59 KB
#!/usr/bin/env ruby
require 'benchmark/ips'
require 'matrix'
require 'nmatrix'
Benchmark.ips do |x|
first_rows = 10
first_cols = 20
second_rows = 20
second_cols = 40
first_array = Array.new(first_rows) { Array.new(first_cols) { rand } }
second_array = Array.new(second_rows) { Array.new(second_cols) { rand } }
result_array = Array.new(first_rows) { Array.new(second_cols) }
x.report "Array iterative" do
# We already have these values with first_rows, etc.
# But we need to put them here so Array strategy doesn't
# have an unfair advantage over the others.
result_rows = first_array.size
result_cols = second_array[0].size
max_ix = first_array[0].size - 1
0.upto(result_rows-1) do |row_number|
0.upto(result_cols-1) do |col_number|
product = 0.0
0.upto(max_ix) do |ix|
product += (first_array[row_number][ix]*second_array[ix][col_number])
end
result_array[row_number][col_number] = product
end
end
result_array
end
first_matrix = Matrix[*first_array]
second_matrix = Matrix[*second_array]
x.report "MRI Matrix#*" do
first_matrix * second_matrix
end
first_nmatrix = NMatrix[*first_array, dtype: :float64]
second_nmatrix = NMatrix[*second_array, dtype: :float64]
x.report "NMatrix#dot(float64)" do
first_nmatrix.dot(second_nmatrix)
end
first_nmatrix_object = NMatrix[*first_array, dtype: :object]
second_nmatrix_object = NMatrix[*second_array, dtype: :object]
x.report "NMatrix#dot(object)" do
first_nmatrix_object.dot(second_nmatrix_object)
end
x.compare!
end