Dyl*_*lan 7 julia elementwise-operations
我是 julia 的新用户,我正在尝试了解在 julia 中编写快速代码的最佳实践是什么。我主要是在数组/矩阵中进行元素明智的操作。我尝试了一些代码来检查哪一个可以让我获得更高的速度
fbroadcast(a,b) = a .*= b;
function fcicle(a,b)
@inbounds @simd for i in eachindex(a)
a[i] *= b[i];
end
end
a = rand(100,100);
b = rand(100,100);
@btime fbroadcast(a,b)
@btime fcicle(a,b)
Run Code Online (Sandbox Code Playgroud)
使用 for 的功能实现了广播版本的 2 倍左右的速度。两种情况有什么区别?我希望广播在内部循环操作,这与我在 fcicle 上所做的非常相似。最后,有没有什么方法可以通过像 a .*= b 这样的简短语法实现最佳速度?
非常感谢,迪伦
我没想到会这样。这可能是一个性能错误吗?\n
同时,本例中出现的广播性能问题似乎仅出现在 2D 阵列中。以下看起来像一个丑陋的黑客,但它似乎恢复了性能:
\n\nfunction fbroadcast(a,b)\n a, b = reshape.((a, b), :) # convert a and b to 1D vectors\n a .*= b\nend\n\nfunction fcicle(a,b)\n @inbounds @simd for i in eachindex(a)\n a[i] *= b[i];\n end\nend\nRun Code Online (Sandbox Code Playgroud)\n\njulia> using BenchmarkTools\njulia> a = rand(100, 100);\njulia> b = rand(100, 100);\n\njulia> @btime fbroadcast($a, $b);\n 121.301 \xce\xbcs (4 allocations: 160 bytes)\n\njulia> @btime fcicle($a, $b);\n 122.012 \xce\xbcs (0 allocations: 0 bytes)\nRun Code Online (Sandbox Code Playgroud)\n