Julia 基本for循环中的意外内存分配?
我想知道为什么Julia 基本for循环中的意外内存分配?,julia,Julia,我想知道为什么@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)
@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
- 每个元素真的有一个alloc吗?(这会破坏性能…)
您正在对全局变量
v
的访问进行基准测试,这是您应该首先了解的
使用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> 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)