Skip to content
Tutorials Center
My learning

Topics

Lesson 120 of 146 ยท Advanced Swift

Profiling with Instruments and Benchmarking

Find real Swift bottlenecks with Instruments: Time Profiler, Allocations, signposts and points of interest, plus how to write fair micro-benchmarks with ContinuousClock.

Performance Tips ended with the most important rule: measure before you change anything. This lesson is about how to measure. Programmers are bad at guessing where time goes, so the professional workflow is always the same: reproduce a slow scenario, record it with a profiler, read the result, change one thing, and record again.

Apple's profiler is called Instruments. It ships with Xcode and runs on macOS, so the Instruments part of this lesson is read-only: you cannot start it from this page. The ideas, though, are not tied to Apple. Sampling profilers, allocation tracking and interval markers exist on every platform (perf on Linux, for example), and the code-level techniques below, such as benchmarking with ContinuousClock and counting objects, run right here.

The measuring loop

flowchart LR
    A["Reproduce the slow case"] --> B["Record with a profiler<br/>(release build)"]
    B --> C["Find the hot spot<br/>or the allocation source"]
    C --> D["Change ONE thing"]
    D --> E["Measure again"]
    E -->|"not enough"| B
    E -->|"fast enough"| F["Stop"]

The profiling loop: never optimize without a recording before and after the change.

Three rules make the loop trustworthy:

  1. Profile an optimized build. Debug builds disable most optimizations, so they show costs that do not exist in production (and hide ones that do). In Xcode, Instruments profiles the Release configuration by default for exactly this reason. Use -O (or swift build -c release) on any other platform.
  2. Profile real hardware. The simulator uses your Mac's CPU and memory, not the phone's.
  3. Profile a realistic scenario. A list of three items hides the problem a list of 3,000 shows.

Starting Instruments

In Xcode choose Product > Profile (Cmd+I). Xcode builds in Release mode and opens the Instruments template chooser. From a terminal you can also record with xctrace record --template "Time Profiler" --launch -- ./MyApp. The templates you use most often are:

Template Question it answers
Time Profiler Which functions use the CPU?
Allocations What is allocating memory, and what is never freed?
Leaks Which objects are unreachable but still alive?
Points of Interest How long do my own labeled intervals take?
Swift Concurrency Which tasks and actors are waiting or running?
Hangs / Animation Hitches Why did the main thread freeze or a frame drop?

Time Profiler

The Time Profiler is a sampling profiler. About 1,000 times per second it interrupts your program, records the call stack of every thread, and moves on. After a few seconds you have thousands of stacks. A function that appears in 40 percent of the samples was on the stack for roughly 40 percent of the time.

sequenceDiagram
    participant P as Profiler
    participant T as Your thread
    loop every ~1 ms
        P->>T: pause and read the call stack
        T-->>P: main > load > parse > decode
        P->>T: resume
    end
    P->>P: count how often each frame appears

A sampling profiler periodically captures the call stack and counts how often each function shows up.

Sampling is cheap, so it barely slows the program, but it is statistical: a function that runs for 0.2 ms once may never be sampled. That is fine, because you are hunting for the big costs.

When you look at the recording, these views matter most:

  • Heaviest Stack Trace. Instruments expands the single most expensive call path for you. Start here.
  • Call Tree with "Invert Call Tree". Normally the tree starts at main and goes down to callees. Inverted, it lists the functions where time was actually spent (the leaves) at the top, with their callers below. This answers "who is burning the CPU?" directly.
  • "Hide System Libraries". Hides frames you cannot edit and shows your own code's share. Uncheck it again when the time really is inside a framework call such as JSON decoding, because then the question becomes why you are calling it so often.
  • "Separate by Thread". Shows whether the work is on the main thread (bad for UI) or on a background queue.

The columns are Weight (samples and percent) and Self Weight (time in the function itself, excluding callees). A function with high weight but low self weight is only a pass-through; follow it down to the callee that owns the cost.

What the typical findings look like

Here is the kind of code a Time Profiler recording often points at, and the repair. You can run the difference yourself:

Swift A hot spot and its fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The exact milliseconds depend on the machine, so the program prints a comparison instead. In a Time Profiler recording, the slow version would show Array.removeFirst() and the memory move beneath it at the top of the inverted call tree.

Allocations

Heap allocation is one of the main costs in Swift (see Performance Tips), and the Allocations instrument shows it. Its main controls:

  • All Heap & Anonymous VM lists live memory by type, with the number of instances and total bytes. Sort by Persistent Bytes to see what is using memory now.
  • Transient versus Persistent. A persistent object is still alive; a transient one has been freed. A huge transient count in a hot loop means a lot of allocation churn, which costs time even if memory stays flat.
  • Generations (Mark Generation). Press the button, do the action you suspect (open a screen, close it), press it again. Instruments shows what was allocated between the marks and still lives. If closing a screen leaves 200 objects behind, you have a leak or a cache that never shrinks.
  • Statistics > Call Trees. Pick a type and see which call stack created it.

Instruments also has a Leaks instrument, and Xcode has a Debug Memory Graph button (the three-circles icon). A leaked object in Swift is almost always a retain cycle: two objects, or an object and a closure, holding strong references to each other.

You can see the same signal without Instruments by counting instances yourself. A counter in init and deinit is a tiny stand-in for the Allocations view, and it is a reliable test that a screen's objects really go away:

Swift Counting live objects to find a retain cycle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

After the safe version, every Screen is gone. After the leaky one, three screens are still alive, which is the number the Allocations instrument would show in the "Persistent" column for Screen after you marked a generation and closed the screens. Inside Instruments you would then open the call tree for Screen to find where those objects were created.

Signposts and Points of Interest

A sampling profiler tells you which function is expensive. It does not know what your program was trying to do. Signposts let you label intervals in your own terms ("load profile", "decode feed", "render page") so that Instruments draws them on a timeline next to CPU use. On Apple platforms you use the os framework:

Swift
import os

let signposter = OSSignposter(subsystem: "com.example.feed", category: .pointsOfInterest)

func refreshFeed() async throws {
    let interval = signposter.beginInterval("refresh feed")
    defer { signposter.endInterval("refresh feed", interval) }

    let data = try await download()
    let parseState = signposter.beginInterval("parse")
    let items = try decode(data)
    signposter.endInterval("parse", parseState, "\(items.count) items")

    signposter.emitEvent("store started")
    try store(items)
}

Choosing .pointsOfInterest as the category makes the intervals show up in the Points of Interest instrument. Other categories appear in the os_signpost instrument, where you can filter by subsystem. Useful details:

  • beginInterval returns a state value that you must pass to the matching endInterval. Intervals can nest, and they can overlap across tasks, because the state identifies each one.
  • The optional message at the end ("\(items.count) items") is formatted lazily and costs almost nothing when no tool is attached. Signposts are designed to be left in release builds.
  • emitEvent marks a single moment instead of a range.
  • Instruments reports the count, total, average, minimum and maximum duration of each interval name, and highlights outliers. Fifty fast refreshes and one slow one is a much more useful finding than an average.
  • The older os_signpost function-style API still works, but OSSignposter is the modern Swift interface.

The os module is not available in the runner on this site (it runs Linux), but the idea is easy to imitate. This small tracer prints a nested outline of labeled intervals without any timings, which is exactly the structure a signpost timeline records:

Swift A tiny interval tracer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

In real code you would add timestamps. The point is that labeled, nested intervals turn "the app felt slow" into "parse took 38 ms of a 41 ms refresh".

Benchmarking in code

Instruments is for finding problems. When you want to compare two implementations, or catch a regression in a test, you benchmark in code. A fair micro-benchmark follows a few rules:

  1. Use a monotonic clock. ContinuousClock (counts through sleep) or SuspendingClock (stops while the machine sleeps) never go backwards. Date() can jump when the system clock changes.
  2. Warm up. The first run pays for cold caches, lazy initialization and page faults. Run once and discard it.
  3. Repeat and take a robust statistic. One run is noise. Take the minimum (closest to the true cost) or the median of many runs, never a single value.
  4. Stop the optimizer from deleting your work. If the result is never used, the compiler may remove the whole computation. Use the result: print it, accumulate it, or pass it to a function the compiler cannot see through.
  5. Keep inputs identical and build them outside the timed section.
Swift A small benchmark helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Two things to notice. First, the program compares the two timings and prints a yes or no, because the absolute numbers belong to one machine on one day. Second, @inline(never) on blackHole is a simple trick to keep the optimizer from proving the results are unused.

Testing performance in XCTest

On Apple platforms, XCTest has measure { }, which runs a block ten times and reports the average and standard deviation. In Xcode you can set a baseline, and later runs fail if they are significantly slower:

Swift
import XCTest

final class ParserTests: XCTestCase {
    func testParsingSpeed() {
        let text = String(repeating: "1,2,3,4,5,", count: 10_000)
        measure {
            _ = parse(text)
        }
    }

    func testAllocationsOfDecode() {
        measure(metrics: [XCTMemoryMetric(), XCTCPUMetric()]) {
            _ = decodeLargeFixture()
        }
    }
}

For serious benchmarking, Apple's open source swift-collections-benchmark and the package-benchmark package from Ordo One run many iterations, report percentiles, count allocations and syscalls, and can compare against a stored baseline in CI. They are not part of the standard toolchain, so add them as development dependencies (see Swift Package Manager). The new Swift Testing library from Testing in Swift has no benchmark feature yet, so use one of these for performance checks.

Pitfalls that fool benchmarks

  • Measuring a debug build. Always use release.
  • Dead code elimination. A loop whose result is unused takes zero time.
  • Constant folding. fib(30) with a literal argument may be computed at compile time. Take inputs from an array or from CommandLine.arguments.
  • Thermal throttling and background load. Phones slow down when hot. Run on a quiet machine and repeat.
  • Measuring the wrong thing. Building the test data inside the timed block measures the data generator.
  • Averaging. One slow run (a garbage-collector-style pause, a context switch) skews the mean. The median or minimum resists it.

Other tools worth knowing

  • -Xfrontend -debug-time-function-bodies (passed through swiftc) reports which functions are slow to type-check, for when the compiler is slow rather than your program. See also Swift Package Manager.
  • perf and valgrind --tool=callgrind on Linux give similar sampling and call-graph views to Time Profiler. Swift symbol names are mangled; pipe them through swift demangle.
  • MetricKit collects battery, hang and launch-time statistics from real users after release, so you see problems that never appear on your desk.
  • Memory Graph and leaks: the leaks command-line tool on macOS lists leaked objects of a running process.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should you profile a Release (optimized) build?

    Optimization removes allocations, inlines calls and specializes generics. A debug profile therefore misleads you about what is actually slow.
  2. 2. What does a sampling profiler such as Time Profiler record?

    It captures stacks about a thousand times per second. A function that appears in many samples was on the stack for a large share of the time.
  3. 3. What is the purpose of OSSignposter intervals?

    Signposts add meaning to a recording: you see how long 'parse' or 'refresh feed' took, not just which low-level functions ran.
  4. 4. Which statistic is most robust for a micro-benchmark with only a few runs?

    The first run pays for cold caches, and a single slow run skews the mean. The median or minimum resists those outliers.
  5. 5. In the Allocations instrument, what does marking a generation before and after an action show you?

    Objects that survive after you closed the screen are candidates for leaks, such as retain cycles.

Summary

  • Measure first: reproduce, record in a release build on real hardware, change one thing, record again.
  • Time Profiler samples call stacks; use Heaviest Stack Trace, the inverted call tree and "Hide System Libraries" to find the real hot spot.
  • Allocations shows live and transient objects by type; mark generations around an action to find leaks and churn, and count instances in init/deinit for a quick check.
  • OSSignposter intervals and events label your own work in the Points of Interest instrument and can stay in release builds.
  • Benchmark in code with ContinuousClock: warm up, repeat, use the median or minimum, keep the result alive and build inputs outside the timed section.
  • Beware debug builds, dead-code elimination, constant folding and averaging one-off outliers.

Next: Swift on Apple platforms