= 0
total = 1e6
n
@time for i in 1:n
global total += i
end
0.258970 seconds (4.15 M allocations: 83.561 MiB, 5.19% gc time, 47.93% compilation time)
Marie-Hélène Burle
If there is one thing you need to remember from this lesson, it is to avoid global variables (that is, avoid variables defined in the global environment).
Scope of variables: Environment within which a variables exist
Global scope: Global environment of a module
Local scope: Environment within a function, a loop, a struct, a macro, etc.
The Julia compiler is not good at optimizing code using global variables. Part of the reason is that their type can change.
We will use the @time
macro to time a loop:
0.258970 seconds (4.15 M allocations: 83.561 MiB, 5.19% gc time, 47.93% compilation time)
Note the garbage collection (gc) time: 14% of total time.
Garbage collection time is a sign of poor code.
0.025520 seconds (2.00 M allocations: 30.518 MiB)
We get a 7.5 speedup.
The memory allocation also decreased by more than half.
For more accurate performance measurements, you should use the @btime
macro from the BenchmarkTools package which excludes compilation time from the timing, averages metrics over multiple runs, and is highly customizable.