julia - 元素明智的操作数组朱莉娅
问题描述
我是一个新的 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)
使用带有 for 的函数实现了广播版本的大约 2 倍的速度。两种情况有什么区别?我希望广播在内部循环操作与我在 fcicle 上所做的非常相似。最后,有没有什么方法可以使用像 a .*= b 这样的简短语法来实现最佳速度?
非常感谢,迪伦
解决方案
我没想到会这样。会不会是性能错误?
同时,在这种情况下表现出的广播性能问题似乎只出现在 2D 阵列中。以下看起来像一个丑陋的黑客,但它似乎恢复了性能:
function fbroadcast(a,b)
a, b = reshape.((a, b), :) # convert a and b to 1D vectors
a .*= b
end
function fcicle(a,b)
@inbounds @simd for i in eachindex(a)
a[i] *= b[i];
end
end
julia> using BenchmarkTools
julia> a = rand(100, 100);
julia> b = rand(100, 100);
julia> @btime fbroadcast($a, $b);
121.301 μs (4 allocations: 160 bytes)
julia> @btime fcicle($a, $b);
122.012 μs (0 allocations: 0 bytes)
推荐阅读
- python - 如何让另一个网络上的人使用 django 访问我的网站
- react-native - undefined 不是对象 options.routeGetIdList[action.payload.name]
- r - ggplot2:facet_grid 中 x 轴标签的条件格式
- azure - 认知服务显示填词和隐藏个人数据
- mysql - 搜索查询特定时间段内的帖子
- openlayers - 如何在 openlayers 6 中对不同类型的几何图形进行聚类?
- php - 显示项目价格包括。不包括。WooCommerce 电子邮件通知中多列的增值税
- javascript - 使用数组 JavaScript 更新 DOM
- python - 获取请求的资源上不存在“Access-Control-Allow-Origin”标头。GCP 和烧瓶
- nestjs - 使用 Nestjs 测试模块进行单元测试有什么好处?