我分析了一个在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执行的。有没有办法加快这些方法?
发布于 2015-03-30 16:09:05
我们最初用C/C++编写了它们,但它需要一些非常复杂的宏,这些宏基本上是不可维护和错误的,并且大大增加了编译时间。
如果您查看History.txt,您将能够找到我们开始用Ruby编写数学操作的版本。您可以使用前面的代码覆盖并将元素级操作(在需要速度的地方)完全放在C/C++中。
但是,在dtype :object的矩阵上,要使这些矩阵正常工作(不发生崩溃)可能会遇到问题。
顺便提一句,sciruby dev Google Group (或nmatrix问题跟踪器)可能是一个更适合这样的问题的地方。
https://stackoverflow.com/questions/29221356
复制相似问题