class Mat_Array attr_reader :n def initialize(n) @n = n @data = Array.new(n){ Array.new(n){ 0 } } end def [](i, j) return @data[i][j] end def []=(i, j, value) @data[i][j] = value end def *(other) result = Mat_Array.new(n) for i in 0...n for j in 0...n for k in 0...n result[i, j] += self[i, k] + other[k ,j] end end end end end class Mat_Table attr_reader :n def initialize(n) @n = n @data = Table.new(n, n) end def [](i, j) return @data[i, j] end def []=(i, j, value) @data[i, j] = value end def *(other) result = Mat_Array.new(n) for i in 0...n for j in 0...n for k in 0...n result[i, j] += self[i, k] + other[k ,j] end end end end end def test_array t = Time.now a = Mat_Array.new(100) b = Mat_Array.new(100) a * b p Time.now - t end def test_table t = Time.now a = Mat_Table.new(100) b = Mat_Table.new(100) a * b p Time.now - t end
class Mat_Array
attr_reader :n
def initialize(n)
@n = n
@data = Array.new(n){ Array.new(n){ 0 } }
end
def [](i, j)
return @data[i][j]
end
def []=(i, j, value)
@data[i][j] = value
end
def *(other)
result = Mat_Array.new(n)
for i in 0...n
for j in 0...n
for k in 0...n
result[i, j] += self[i, k] + other[k ,j]
end
end
end
end
end
class Mat_Table
attr_reader :n
def initialize(n)
@n = n
@data = Table.new(n, n)
end
def [](i, j)
return @data[i, j]
end
def []=(i, j, value)
@data[i, j] = value
end
def *(other)
result = Mat_Array.new(n)
for i in 0...n
for j in 0...n
for k in 0...n
result[i, j] += self[i, k] + other[k ,j]
end
end
end
end
end
def test_array
t = Time.now
a = Mat_Array.new(100)
b = Mat_Array.new(100)
a * b
p Time.now - t
end
def test_table
t = Time.now
a = Mat_Table.new(100)
b = Mat_Table.new(100)
a * b
p Time.now - t
end
Table比Array快一点,但是二者应该是在一个量级上的。
这里测试Array跑完一次矩阵乘法需要3.5s,Table需要3.0s左右,我特地使用了效率低的写法。
感觉处理这类问题,浪费的时间应该在元素的读取上,如果用改良的写法能提高一倍的效率。 |