Performance

Author

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).

Definitions

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.

Why avoid global variables?

The Julia compiler is not good at optimizing code using global variables. Part of the reason is that their type can change.

Example

We will use the @time macro to time a loop:

  • In the global environment:
total = 0
n = 1e6

@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)

Note the garbage collection (gc) time: 14% of total time.

Garbage collection time is a sign of poor code.

  • In a local environment (a function):
function local_loop(total, n)
    total = total
    @time for i in 1:n
        global total += i
    end
end

local_loop(0, 1e6)
  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.