Training Modules 2021
Basics of the Julia language

Peformance

The one thing you need to remember:

Avoid global variables

Scope of variables

Environment within which a variable exists

Global scope

Global environment of a module

Local scope

e.g. within a function, a loop, a struct, a macro

Why?

The Julia compiler is not good at optimizing code using global variables

Part of the reason is that their type can change

Example

In the global environment:

total = 0
n = 1e6

@time for i in 1:n
    global total += i
end

Example

In a local environment:

function local_loop(total, n)
    total = total
    @time for i in 1:n
        global total += i
    end
end

local_loop(0, 1e6)

Measuring performance tips

We just saw the @time macro

Look for garbage collection output: this is a sign that something is really not optimized

Look also at the memory allocation

Measuring performance tips

You can also use the @btime macro from the BenchmarkTools package It averages times over multiple runs, excludes compilation time, and is customizable

More advanced performance tips

... in the Julia documentation
Questions?