tezvyn:

measure: Baseline and Compare Code Performance

AI-drafted, machine-checkedSource: developer.apple.comadvanced
measure: Baseline and Compare Code Performance

`measure` in XCTest establishes a performance baseline for a block of code and fails tests if it regresses. It tracks critical algorithm speed, running the code ten times for a stable average. The footgun is ignoring the baseline: you must set it first.

WHY IT EXISTS: Manually timing code with Date() is imprecise and tedious. We need a standardized, repeatable way to detect performance regressions in critical code paths directly within our test suite, preventing slow changes from shipping unnoticed.

THE MENTAL MODEL: Think of measure as a stopwatch with a memory. The first time you run it, you're setting a "lap time" (the baseline). On every subsequent run, it compares the new lap time to the saved one. If you're suddenly much slower, the test fails.

HOW IT WORKS: Inside an XCTestCase, you call self.measure { ... }. The code inside the closure is executed 10 times to warm up and gather a stable sample. XCTest calculates the average execution time and the standard deviation. The first time a test runs, you must edit the test and click the gray diamond icon next to the measure block to "Set Baseline". This saves the measured performance into your project's test plan. Future test runs will compare against this saved baseline. If the new average time exceeds the baseline by a configurable threshold (default is 10%), the test fails.

WHEN TO USE IT: Use measure for hot paths in your application where performance is critical. Three places this shows up: first, complex calculations or rendering logic; second, data serialization and deserialization, like with JSON or Codable; third, tight loops within a core algorithm. It's for micro-benchmarking specific, isolated units of work.

WHEN NOT TO USE IT: Do not use measure for code with high-variance external dependencies like network requests; the unpredictable latency will make the test flaky. It is also not for measuring UI responsiveness from a user's perspective. For that, use XCUITest or the Instruments tool, as measure only tracks raw code execution speed, not perceived app performance.

ONE CANONICAL EXAMPLE: A developer wants to ensure their custom data processing function remains fast. They write a performance test: func test_DataProcessingPerformance() { self.measure { let _ = MyProcessor.process(data: largeDataset) } }. They run the test once, set the baseline in Xcode, and commit the result. Now, any future code change that slows down MyProcessor.process will cause this test to fail, alerting the team to the regression before it ships.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.