An XCTest performance test for a service-log parser never fails on CI despite a threefold slowdown; what does measure(metrics:) compare its results against?
answer
- recording is not judging
- first iteration thrown away
- elapsed time includes idle time
- a saved baseline plus max STDDEV
- a gutter dot means no comparison
basics
~20 smeasure(metrics:) records each metric over several runs of the block and fails only when a saved baseline exists and the result is worse than it by more than the allowed standard deviation. Without a baseline for that run, it only records.
solid answer
~40 s`measure(metrics:block:)` runs the block `iterationCount + 1` times (5 + 1 by default), discards the first run, and records each metric, such as `XCTClockMetric` for elapsed time and `XCTMemoryMetric` for the change in physical memory. It judges nothing on its own. A performance test fails only when a **baseline** has been set in Xcode and the measured value is worse than that baseline by more than its max standard deviation. A run with no baseline to compare against just records, shown in Xcode as a gray icon with a dot. A baseline saved from a developer's Mac and simulator says nothing about different CI hardware. Apple also recommends measuring a Release build with Debug executable, code coverage and sanitizers turned off.
code
swift · 19 linesimport XCTest
struct ServiceLogParser {
func parse(_ text: String) -> [Substring] { text.split(separator: "\n") }
}
final class ServiceLogParserPerformanceTests: XCTestCase {
func testParsingTenThousandEntries() {
let log = (1...10_000).map { "\($0 * 15),oil change" }.joined(separator: "\n")
let parser = ServiceLogParser()
let options = XCTMeasureOptions()
options.iterationCount = 10 // the block runs 11 times; the first is discarded
measure(metrics: [XCTClockMetric(), XCTMemoryMetric()], options: options) {
_ = parser.parse(log)
}
}
}go deeper
Recall that measure runs a block several times and records metrics such as elapsed time. Know that the test can fail only against a saved baseline.
Explain iterationCount plus one discarded run, what each metric records, and how manuallyStart with startMeasuring() keeps setup out of the numbers.
Diagnose a performance test that never fails: no baseline for that run, a baseline from different hardware, a Debug build, or baselines accepted after every red result.
Decide whether performance tests gate merges at all: they need stable hardware and owned baselines, or they stay advisory while real regressions are tracked from field metrics.
## What measure(metrics:) actually does A performance test is an ordinary test method that calls one of `XCTestCase`'s measure functions. The modern form takes an array of **metrics**: - `measure(metrics:block:)` measures the given metrics with the class's default options. - `measure(metrics:options:block:)` adds an `XCTMeasureOptions`. - `measure(options:block:)` uses `defaultMetrics`, which is `[XCTClockMetric()]` unless a subclass overrides it, and `measure(_:)` records elapsed seconds by default. With default options the block runs **`iterationCount + 1`** times, `iterationCount` being 5, and the first iteration is discarded to reduce warm-up variance from caches and other first-run work. Xcode then shows the recorded values and their average for each metric. ## The metrics | Metric | What it records | |---|---| | `XCTClockMetric` | elapsed time, measured monotonically, including time the CPU is idle or running other code | | `XCTCPUMetric` | CPU time, cycles and instructions retired for the measured target | | `XCTMemoryMetric` | the difference in physical memory use from before the block to after it | | `XCTStorageMetric` | bytes logically written to storage | All four are available from iOS 13. Pick the metric that matches the budget: a parser with a speed budget wants `XCTClockMetric`, and `XCTCPUMetric` when waits inside the block would blur the number; a parser suspected of keeping a large buffer wants `XCTMemoryMetric`. ## When a performance test fails Recording is not judging. Apple's documentation describes the rule: 1. A **baseline** is a value saved in Xcode for a metric of that test, set from the performance report with **Set Baseline**, or by editing it, or by accepting the current average. 2. A **max STDDEV** sets how far worse than the baseline a result may be. 3. The test fails when the recorded metric is worse than the baseline by more than that deviation. 4. When no baseline exists to compare against, XCTest only records the values; Xcode marks the call with a gray icon and a dot, while a checkmark means the values were compared. So a threefold slowdown passes for as long as the run has nothing to compare against. A number like elapsed time is a property of the machine that produced it: a baseline accepted on a developer's Mac and simulator is not a meaningful threshold for different CI hardware, so a team that wants CI to catch regressions has to record and maintain baselines from the hardware that runs the check. ## Setting and maintaining a baseline in Xcode Apple's workflow for the baseline is short: 1. Run the test once, then click the icon beside the measure call to open the performance report, which graphs the recent values with their average. 2. Click **Set Baseline** to save the current average. 3. Later, click **Edit** to type a new baseline or click **Accept** to adopt the current average, and enter the **Max STDDEV**. 4. Click **Save**. Accepting is a decision, not a chore: every accepted regression becomes the new normal for every later run. ## Measuring the right thing - **Measure only the work.** Building the 10 000-line log inside the block adds its cost to every iteration. Build it outside, or use `XCTMeasureOptions.invocationOptions` with `manuallyStart` and call `startMeasuring()` inside the block. - **Raise `iterationCount`** when results are noisy; the block still runs one extra, discarded time. - **Measure realistic builds.** Apple's guidance is to build for testing with the Release configuration, turn off Debug executable, and disable code coverage and runtime sanitizers for the performance test plan; configuring schemes and test plans is covered with Xcode. - **Profile a failure.** From a failing performance test Xcode offers to open it in Instruments, which is where the cause is found. ## Common mistakes - Treating a green performance test as proof of speed when the gutter shows a dot, not a checkmark. - Accepting a new baseline every time the test fails, which turns the check into a recorder. - Measuring the simulator in Debug and comparing the number with a device build. - Reading `XCTClockMetric` as CPU work: it also counts time spent waiting. - Expecting `executionTimeAllowance` to catch a slowdown; it is a guard against hangs, not a performance budget.
- How do you keep setup work out of a measured block?Do it before calling `measure`, or, when it must happen every iteration, pass `XCTMeasureOptions` whose `invocationOptions` include `manuallyStart` and call `startMeasuring()` inside the block after the setup. `manuallyStop` with `stopMeasuring()` does the same for work at the end of each iteration.
- What is the difference between XCTClockMetric and XCTCPUMetric for a parser test?`XCTClockMetric` records elapsed time, including time the CPU is idle or running other code. `XCTCPUMetric` records CPU time, cycles and instructions retired for the measured target, which do not grow while the code waits. For a parser that only computes, the two should move together; once the block waits on I/O or a lock, CPU time shows the work and clock time shows the wait.
Like a car's fuel-economy figure: the number means something only against a reference measured on the same car and route. measure(metrics:) writes down the trip computer's readings; without a reference figure recorded for that car, nobody declares the trip a failure.
- A green performance test proves the code is as fast as before.
- measure() fails whenever a run is slower than the previous one.
- XCTClockMetric counts only the CPU time spent in the block.
- A baseline from a laptop simulator is a valid threshold on any CI machine.
- executionTimeAllowance is the right way to enforce a speed budget.