我想知道为什么 @btime
在像下面这样的基本循环中报告每个元素的内存分配:
julia> using BenchmarkTools
julia> v=[1:15;]
15-element Array{Int64,1}:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
julia> @btime for vi in v end
1.420 μs (15 allocations: 480 bytes)
julia> @btime for i in eachindex(v) v[i]=-i end
2.355 μs (15 allocations: 464 bytes)
我不知道如何解释这个结果:
- 它是
@btime
的错误/工件吗? - 每个元素真的有一个分配吗? (这会破坏性能...)
julia> versioninfo()
Julia Version 1.5.1
Commit 697e782ab8 (2020-08-25 20:08 UTC)
Platform Info:
OS: Linux (x86_64-pc-linux-gnu)
CPU: Intel(R) Xeon(R) CPU E5-2603 v3 @ 1.60GHz
WORD_SIZE: 64
LIBM: libopenlibm
LLVM: libLLVM-9.0.1 (ORCJIT, haswell)
最佳答案
您正在对全局变量 v
的访问进行基准测试,这是第一个 performance tip你应该知道。
使用 BenchmarkTools
,您可以通过插入 v
来解决这个问题:
julia> @btime for vi in v end
555.962 ns (15 allocations: 480 bytes)
julia> @btime for vi in $v end
1.630 ns (0 allocations: 0 bytes)
但请注意,通常最好将代码放在函数中。全局范围对性能不利:
julia> f(v) = for vi in v end
f (generic function with 1 method)
julia> @btime f(v)
11.410 ns (0 allocations: 0 bytes)
julia> @btime f($v)
1.413 ns (0 allocations: 0 bytes)
关于julia - 基本for循环中的意外内存分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66421523/