Created
August 23, 2019 01:05
-
-
Save dwhite96/2557a62f7d796cce54e4382d411b8578 to your computer and use it in GitHub Desktop.
Matrix Benchmarking
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
require 'benchmark' | |
class Matrix1 | |
attr_reader :rows | |
def initialize(matrix_string) | |
@rows = convert(matrix_string) | |
end | |
def columns | |
@rows.transpose | |
end | |
private | |
def convert(matrix_string) | |
matrix_string.scan(/([^\n]+)/).map do |row| | |
row[0].split.map(&:to_i) | |
end | |
end | |
end | |
class Matrix2 | |
attr_reader :rows | |
def initialize(matrix_string) | |
@rows = convert(matrix_string) | |
end | |
def columns | |
@rows.transpose | |
end | |
private | |
def convert(matrix_string) | |
matrix_string.each_line.map do |row| | |
row.split.map(&:to_i) | |
end | |
end | |
end | |
# ************ TEST CODE *************** | |
def test_small_row_using_matrix_1 | |
Matrix1.new("1 2\n10 20") | |
end | |
def test_small_row_using_matrix_2 | |
Matrix2.new("1 2\n10 20") | |
end | |
def test_large_row_using_matrix_1 | |
Matrix1.new("9 8 7 6 5 4 3 2 1 0\n19 18 17 16 15 14 13 12 11 10") | |
end | |
def test_large_row_using_matrix_2 | |
Matrix2.new("9 8 7 6 5 4 3 2 1 0\n19 18 17 16 15 14 13 12 11 10") | |
end | |
def test_large_column_using_matrix_1 | |
Matrix1.new("1 2 3\n4 5 6\n7 8 9\n10 11 12\n13 14 15\n16 17 18\n19 20 21\n22 23 24\n25 26 27\n28 29 30") | |
end | |
def test_large_column_using_matrix_2 | |
Matrix2.new("1 2 3\n4 5 6\n7 8 9\n10 11 12\n13 14 15\n16 17 18\n19 20 21\n22 23 24\n25 26 27\n28 29 30") | |
end | |
if __FILE__ == $0 | |
Benchmark.bmbm do |x| | |
x.report('Small row - Matrix 1:') { test_small_row_using_matrix_1 } | |
x.report('Small row - Matrix 2:') { test_small_row_using_matrix_2 } | |
x.report('Large row - Matrix 1:') { test_large_row_using_matrix_1 } | |
x.report('Large row - Matrix 2:') { test_large_row_using_matrix_2 } | |
x.report('Large column - Matrix 1:') { test_large_column_using_matrix_1 } | |
x.report('Large column - Matrix 2:') { test_large_column_using_matrix_2 } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment