High-Performance Tips

Motivation and Goals

Motivation
  • We want to write faster functions.
  • We want to give AI specific instructions to improve computational speed.
Learning Goals
  • Measure runtime and memory allocations.
  • Use a profiler to locate bottlenecks.
  • Understand three rules that affect performance.

Performance Tips for Economists

  • Julia’s official Performance Tips cover a broad range of techniques.
  • This lecture focuses on the performance of user-written numerical functions, which matters when we do estimation.

Topics Not Covered

  • Algorithm design
    • This is the most critical factor, but out of the scope of this module.
  • Parallel computing
    • Dividing tasks wisely by parallel computing is also critical. The codes for econ research suits (bootstrap, grid search, etc)
    • I will cover this topic in the later class.

Measurement and Diagnostic Tools

  • Before optimizing a function, we need to know
    • how to measure runtime and memory allocations and
    • how to locate bottlenecks within the function.

BenchmarkTools

  • BenchmarkTools runs an expression repeatedly to reduce measurement noise.

  • @btime reports runtime and memory allocations. Interpolate external values with $.

  • The following functions compute the mean squared error of a fitted OLS model using vectorized syntax and an explicit loop.

using BenchmarkTools
using Random
using Statistics

function mse_vectorized(y, fitted)
    return mean((y .- fitted).^2)
end

function mse_loop(y, fitted)
    squared_residuals = similar(y)

    for i in eachindex(y, fitted)
        squared_residuals[i] = (y[i] - fitted[i])^2
    end

    return mean(squared_residuals)
end

Random.seed!(1234)
n, k = 10_000, 10
X = randn(n, k)
beta_true = randn(k)
y = X * beta_true + randn(n)
beta_hat = X \ y
fitted = X * beta_hat

@assert mse_vectorized(y, fitted) ≈ mse_loop(y, fitted)
@btime mse_vectorized($y, $fitted);
@btime mse_loop($y, $fitted);
  2.906 μs (3 allocations: 80.06 KiB)
  2.771 μs (3 allocations: 80.06 KiB)
  • The two implementations have similar runtime and memory use. In Julia, an explicit loop does not carry an inherent performance penalty relative to vectorized syntax.

  • The same comparison can use a preallocated output vector:

function squared_residuals_broadcast!(out, y, fitted)
    @. out = (y - fitted)^2
    return out
end

function squared_residuals_loop!(out, y, fitted)
    for i in eachindex(out, y, fitted)
        out[i] = (y[i] - fitted[i])^2
    end
    return out
end

broadcast_result = similar(y)
loop_result = similar(y)

squared_residuals_broadcast!(broadcast_result, y, fitted)
squared_residuals_loop!(loop_result, y, fitted)
@assert broadcast_result ≈ loop_result

@btime squared_residuals_broadcast!($broadcast_result, $y, $fitted);
@btime squared_residuals_loop!($loop_result, $y, $fitted);
  1.479 μs (0 allocations: 0 bytes)
  1.988 μs (0 allocations: 0 bytes)
  • With preallocated output, both broadcast and the explicit loop can run without memory allocations.

Profile

  • Profile samples a running program to identify where it spends time.
using Profile

function light_calculation(x)
    total = 0.0
    for _ in 1:10
        total += sum(sin, x)
    end
    return total
end

function heavy_calculation(x)
    total = 0.0
    for _ in 1:100
        total += sum(sin, x)
    end
    return total
end

function combined_calculation(x)
    return light_calculation(x) + heavy_calculation(x)
end

profile_input = randn(100_000)
combined_calculation(profile_input)  # Compile before profiling.

Profile.clear()
profile_task = @task combined_calculation(profile_input)
@profile fetch(schedule(profile_task))
Profile.print(
    IOContext(stdout, :color => false);
    format = :tree,
    maxdepth = 5,
    noisefloor = 0.0,
    tasks = UInt(pointer_from_objref(profile_task)),
)
Overhead ╎ [+additional indent] Count File:Line  Function
=========================================================
 ╎52 …h_performance_tips.qmd:156  (::Main.Notebook.var"#2#3")()
 ╎ 52 …h_performance_tips.qmd:149  combined_calculation(x::Vector{Float64})
 ╎  46 …h_performance_tips.qmd:143  heavy_calculation
 ╎   46 @Base/reducedim.jl:980  sum
 ╎    46 @Base/reducedim.jl:980  #sum#736
 ╎     46 @Base/reducedim.jl:984  _sum
 ╎  6  …h_performance_tips.qmd:135  light_calculation
 ╎   6  @Base/reducedim.jl:980  sum
 ╎    6  @Base/reducedim.jl:980  #sum#736
 ╎     6  @Base/reducedim.jl:984  _sum
Total snapshots: 55. Utilization: 100% across all threads and tasks. Use the `groupby` kwarg to break down by thread and/or task.
  • Each count is the number of snapshots in which the function was active, not an exact timing; larger counts indicate likely bottlenecks.

How Julia Executes Code

  • Julia usually generates specialized machine code when a function is first called with a new combination of argument types.
  • For example, these two calls use different argument types:
f(x) = x + 1

f(1)    # First call with an Int64
f(1.0)  # First call with a Float64
2.0
  • The process is:
    • A function is called with concrete argument types.
    • Julia infers the types of intermediate values inside the function.
    • Julia generates machine code specialized for those argument types.
    • Later calls with the same argument types reuse the compiled code.
  • This specialization is one reason why Julia can execute numerical code quickly.
  • Writing type-stable functions helps Julia generate efficient machine code.
    • This idea corresponds to Rules 1 and 2.

Rules for high performance

Rule 1: Put performance-critical code in functions

  • Put numerical loops in functions and pass their inputs as arguments.
  • A non-constant global can change type, which makes optimization difficult.
performance_data = rand(100_000)

function sum_from_global()
    total = 0.0
    for value in performance_data
        total += value
    end
    return total
end

function sum_from_argument(data)
    total = 0.0
    for value in data
        total += value
    end
    return total
end

@assert sum_from_global() ≈ sum_from_argument(performance_data)
@btime sum_from_global();
@btime sum_from_argument($performance_data);
  4.322 ms (399490 allocations: 7.62 MiB)
  69.917 μs (0 allocations: 0 bytes)
  • Both functions use the same loop. Passing the data as an argument gives Julia the concrete input type needed for specialization.
  • Type annotations on function arguments are not required for specialization.
  • Setup and function calls can remain at the top level. Use const for global values that will not be rebound.

Practical example: DataFrames

  • A DataFrame is flexible but not type-stable. Avoid using DataFrameRow directly inside performance-critical loops.
using DataFrames

df = DataFrame(y = randn(100_000), fitted = randn(100_000))

function mse_rows(df)
    total = 0.0
    for row in eachrow(df)
        residual = row.y - row.fitted
        total += residual^2
    end
    return total / nrow(df)
end

function mse_kernel(y, fitted)
    total = 0.0
    for i in eachindex(y, fitted)
        residual = y[i] - fitted[i]
        total += residual^2
    end
    return total / length(y)
end

function mse_columns(df)
    return mse_kernel(df.y, df.fitted)
end

@assert mse_rows(df) ≈ mse_columns(df)
@btime mse_rows($df);
@btime mse_columns($df);
  12.293 ms (998982 allocations: 15.24 MiB)
  73.209 μs (1 allocation: 16 bytes)
  • This pattern is called a function barrier: the outer function can accept a DataFrame, while the kernel function receives concrete column vectors.
  • Pass columns, not rows, to performance-critical functions.

Rule 2: Write type-stable code

  • A function is type-stable when Julia can infer its intermediate and return types from its input types.

Type-unstable and type-stable functions

function positive_part_unstable(x)
    if x > 0
        return x
    else
        return 0
    end
end

function positive_part_stable(x)
    if x > 0
        return x
    else
        return zero(x)
    end
end

Diagnose with @code_warntype

using InteractiveUtils
@code_warntype positive_part_unstable(1.0)
@code_warntype positive_part_stable(1.0)
  • The key lines from the output are:
Type-unstable function
Arguments
  x::Float64
Body::Union{Float64, Int64}

Type-stable function
Arguments
  x::Float64
Body::Float64
  • Arguments shows that both functions receive x::Float64.
  • Body shows the inferred return type:
    • Union{Float64, Int64} means that the return type is not concrete.
    • Float64 means that Julia inferred one concrete return type.
  • Types after :: show Julia’s inference for intermediate values.
  • Focus on unexpected Any or Union types in performance-critical code.
  • Use @btime to confirm that the type instability affects performance.

How to write type-stable code

  • Give each function one return contract.
    • For example, use separate mean_moment(contributions) and moment_contributions(contributions) functions instead of one function that returns either a scalar or a vector.
  • Initialize accumulators from the input type.
    • For example, use total = zero(eltype(values)) instead of total = 0.
  • Match numeric literals to existing values.
    • For example, use zero(x) and one(x) instead of 0 and 1.
  • Convert or extract dynamic inputs once, then pass concrete values to a kernel function.
    • For example, extract y = df.y and pass y to mse_kernel(y, fitted).
  • Do not add argument type annotations only for performance.
    • For example, Julia specializes f(x) when it is called with a Float64; writing f(x::Float64) is not faster for that call.

Rule 3: Reduce allocations inside repeatedly called functions

  • Allocations are not inherently bad, but repeated allocations increase garbage collection.
  • If a function repeatedly produces an array of the same size, preallocate the output and reuse it.
  • If a function returns only a scalar summary, accumulate the scalar directly instead of creating temporary arrays.
function residuals_allocating(y, fitted)
    return y .- fitted
end

function residuals!(out, y, fitted)
    @. out = y - fitted
    return out
end

residual_buffer = similar(y)

@assert residuals_allocating(y, fitted) ≈ residuals!(residual_buffer, y, fitted)
@btime residuals_allocating($y, $fitted);
@btime residuals!($residual_buffer, $y, $fitted);
  1.722 μs (3 allocations: 80.06 KiB)
  1.917 μs (0 allocations: 0 bytes)
  • residuals_allocating creates a new vector each time it is called.
  • residuals! reuses residual_buffer. By convention, a function ending in ! may modify one of its arguments.
  • Use @btime to compare allocations before and after the change.

Other tips

  • Julia’s dense arrays store matrices in column-major order.
    • In nested loops, vary the row index in the inner loop and the column index in the outer loop. This accesses the matrix one column at a time.
function sum_column_major(A)
    total = zero(eltype(A))

    for j in axes(A, 2)
        for i in axes(A, 1)
            total += A[i, j]
        end
    end

    return total
end
  • Use the backslash operator (\) to solve linear systems and least-squares problems.
    • For dense numerical arrays, it uses optimized factorization routines and avoids explicitly computing a matrix inverse.
using LinearAlgebra

beta_hat = X \ y
mul!(fitted, X, beta_hat)

Checklist

  • Put performance-critical code in functions.
  • Write type-stable code.
  • Reduce allocations inside repeatedly called functions.

Applying these rules with AI

  • Ask AI to read these rules before it writes performance-critical code.
  • When asking AI to revise code, use prompts such as:
    • “I want to speed up this function. Diagnose the bottlenecks and rank them by their contribution to runtime. Explain each proposed fix. Distinguish implementation changes from changes to the computational logic.”
    • “Implement suggestions X, Y, and Z one at a time. After each change, verify that the outputs match the original function for at least 10 sufficiently varied inputs.”