访问矩阵时SPLAT操作员的性能

发布于 2025-02-12 13:06:41 字数 511 浏览 2 评论 0原文

假设我们有一个矩阵和要访问该矩阵的指数的矩阵和向量:

matrix = Matrix{Float64}(undef, 5000, 4000)
point = [1244, 3353]

我们可以使用Splat Operator(...)扩展点向量以访问矩阵,或者我们可以明确使用点[1 ]和Point [2]作为指数:

matrix[point...]
vs
matrix[point[1], point[2]]

第一个更优雅,但显然也更慢:

@btime $matrix[$point...]
70.083 ns (4 allocations: 64 bytes)

@btime $matrix[$point[1], $point[2]]
1.800 ns (0 allocations: 0 bytes)

这种差异来自何处?有没有办法使SPLAT操作员更具性能,或者如果我关心性能,我应该简单地使用其他解决方案?

Let's say we have a matrix and a vector of the indices at which we want to access that matrix:

matrix = Matrix{Float64}(undef, 5000, 4000)
point = [1244, 3353]

We can use the splat operator (...) to expand the point vector to access the matrix, or we can explicitly use point[1] and point[2] as the indices:

matrix[point...]
vs
matrix[point[1], point[2]]

The first is more elegant, but apparently also much slower:

@btime $matrix[$point...]
70.083 ns (4 allocations: 64 bytes)

@btime $matrix[$point[1], $point[2]]
1.800 ns (0 allocations: 0 bytes)

Where does this difference come from? Is there a way to make the splat operator more performant or should I simply use the other solution if I care about performance?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

负佳期 2025-02-19 13:06:41

元组似乎与明确的破坏一样快:(

julia> @btime $matrix[point...] setup=(point = [1244, 3353])
  91.024 ns (4 allocations: 64 bytes)
0.0

julia> @btime $matrix[point[1], point[2]] setup=(point = [1244, 3353])
  2.530 ns (0 allocations: 0 bytes)
0.0

julia> @btime $matrix[point...] setup=(point = (1244, 3353))
  2.624 ns (0 allocations: 0 bytes)
0.0

julia> @btime $matrix[point[1], point[2]] setup=(point = (1244, 3353))
  2.255 ns (0 allocations: 0 bytes)
0.0

我认为后三个之间的区别大多是微不足道的 - 在较早的试验中,第二个“赢了”。

搭配 如果您直接插入元组,就不足为奇了。

Splatting a tuple seems to be as fast as explicit destruction:

julia> @btime $matrix[point...] setup=(point = [1244, 3353])
  91.024 ns (4 allocations: 64 bytes)
0.0

julia> @btime $matrix[point[1], point[2]] setup=(point = [1244, 3353])
  2.530 ns (0 allocations: 0 bytes)
0.0

julia> @btime $matrix[point...] setup=(point = (1244, 3353))
  2.624 ns (0 allocations: 0 bytes)
0.0

julia> @btime $matrix[point[1], point[2]] setup=(point = (1244, 3353))
  2.255 ns (0 allocations: 0 bytes)
0.0

(I presume the difference between the latter three are mostly insignificant -- in earlier trials, the third "won" over the second.)

Variadic function arguments are internally passed as tuples, so it's no surprise there is no overhead if you directly insert a tuple.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文