提高 Element Wise 数学运算的性能

Improving Performance of Element Wise Math Operations

我正在分析一个对 NMatrix 矩阵执行大量数学运算的应用程序。

应用程序大部分时间都在下面的代码中。

{add: :+, sub: :-, mul: :*, div: :/, pow: :**, mod: :%}.each_pair do |ewop, op|

define_method("__list_elementwise_#{ewop}__") do |rhs|

  self.__list_map_merged_stored__(rhs, nil) { |l,r| l.send(op,r) }.cast(stype, NMatrix.upcast(dtype, rhs.dtype))

end

define_method("__dense_elementwise_#{ewop}__") do |rhs|

  self.__dense_map_pair__(rhs) { |l,r| l.send(op,r) }.cast(stype, NMatrix.upcast(dtype, rhs.dtype))

end

define_method("__yale_elementwise_#{ewop}__") do |rhs|

  self.__yale_map_merged_stored__(rhs, nil) { |l,r| l.send(op,r) }.cast(stype, NMatrix.upcast(dtype, rhs.dtype))

end

end

在代码上方的评论中,它说:

  # Define the element-wise operations for lists. Note that the __list_map_merged_stored__ iterator returns a Ruby Object

  # matrix, which we then cast back to the appropriate type. If you don't want that, you can redefine these functions in

  # your own code.

我不太熟悉 NMatrix 的内部结构,但似乎数学运算是在 Ruby 中执行的。有什么方法可以加速这些方法吗?

我们最初是用 C/C++ 编写的,但它需要一些非常复杂的宏,这些宏基本上无法维护且存在错误,并且大大增加了编译时间。

如果您查看 History.txt,您将能够找到我们在 Ruby 中开始编写数学运算的版本。您可以使用先前的代码来覆盖并专门将元素操作(您需要速度的地方)放在 C/C++.

但是,您可能 运行 无法在 dtype :object.

的矩阵上正常工作(没有崩溃)

附带说明一下,sciruby-dev Google 组(或 nmatrix 问题跟踪器)可能更适合解决此类问题。