Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected memory allocation in basic for loop?

Tags:

julia

I am wondering why @btime reports one memory allocation per element in basic loops like these ones:

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)

I do not know how to interpret this result:

  • is it a bug/artifact of @btime?
  • is there really one alloc per element? (this would ruin performance...)

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)
like image 625
Picaud Vincent Avatar asked Apr 15 '26 00:04

Picaud Vincent


1 Answers

You're benchmarking access to the global variable v, which is the very first performance tip you should be aware of.

With BenchmarkTools you can work around that by interpolating 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)

But note that in general it's better to put your code in functions. The global scope is just bad for performance:

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)
like image 70
giordano Avatar answered Apr 20 '26 01:04

giordano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!