Generated banner for Performance Profiling
Generated logo for Performance Profiling

Performance Profiling

Meng ToCommunityCreated by Meng To

  • Skill
  • Guidelines
  • Software development
  • MIT
  • No issues found

From the author

Guide performance profiling for Apple platform apps with Instruments, Xcode diagnostics, and MetricKit. Use when investigating app hangs, stutters, high CPU, memory leaks, memory growth, OOM crashes, slow launch, battery drain, thermal issues, App Store performance readiness, or when adding os_signpost and measurement hooks.
— the description by Meng To

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured approach to performance profiling for Apple platform apps. It helps developers identify bottlenecks related to CPU usage, memory management, launch times, and energy consumption. By leveraging Xcode instruments, diagnostics, and MetricKit, the skill guides users through a repeatable workflow: identifying the performance category, profiling on physical hardware, applying targeted fixes, and verifying improvements with concrete measurements.

What it does

  • Provides a decision tree to match performance issues with the correct diagnostic tool.
  • Outlines a systematic workflow for profiling, fixing, and verifying performance improvements.
  • Offers specific guidance for CPU, memory, launch time, and energy diagnostics.
  • Recommends Xcode diagnostic settings to detect common runtime issues.
  • Provides code patterns for integrating MetricKit to monitor production performance.
  • Includes a review checklist for responsiveness, memory, launch, and energy best practices.

When to use it

  • When investigating app hangs, stutters, or high CPU usage.
  • When troubleshooting memory leaks, growth, or OOM crashes.
  • When optimizing cold, warm, or resume launch times.
  • When addressing battery drain, thermal throttling, or excessive network usage.
  • When preparing an application for App Store performance readiness.

Advantages

  • Promotes data-driven optimization by prioritizing real-device profiling.
  • Reduces guesswork by mapping specific symptoms to dedicated profiling tools.
  • Encourages sustainable performance through production monitoring with MetricKit.
  • Provides actionable code examples for common performance pitfalls.
  • Standardizes the process of verifying fixes before and after implementation.

Usage examples

“My app is experiencing high CPU usage. How should I investigate?”
The skill directs you to use the Time Profiler instrument, focus on CPU percent by function, and check the call tree weight to identify the specific code path causing the bottleneck.
“How can I reduce my app's cold launch time?”
The skill suggests using the App Launch instrument, reducing dynamic frameworks, removing static initializers, and deferring non-essential initialization code in the app's entry point.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/mengto/performance-profiling/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip performance-profiling.zip -d .agents/skills

Documentation by Meng To

Performance Profiling

Use this skill to diagnose Apple app performance issues systematically, pick the right profiling workflow, apply targeted fixes, and verify the change with real measurements.

Decision Tree

Choose the reference file before changing code:

What performance problem are you investigating?

+ App hangs, stutters, dropped frames, slow UI, high CPU
  -> Read references/time-profiler.md

+ High memory, leaks, OOM crashes, growing footprint
  -> Read references/memory-profiling.md

+ Slow cold launch, warm launch, resume, or time to first frame
  -> Read references/launch-optimization.md

+ Battery drain, thermal throttling, background energy, network waste
  -> Read references/energy-diagnostics.md

+ General "app feels slow"
  -> Start with references/time-profiler.md, then references/memory-profiling.md

+ Pre-release performance audit
  -> Read all reference files and use the review checklist below

Quick Reference

ProblemInstrument / ToolKey MetricReference
UI hangs over 250 msTime Profiler + HangsHang duration, main thread stackreferences/time-profiler.md
High CPU usageTime ProfilerCPU percent by function, call tree weightreferences/time-profiler.md
Memory leakLeaks + Memory GraphLeaked bytes, retain cycle pathsreferences/memory-profiling.md
Memory growthAllocationsLive bytes, generation analysisreferences/memory-profiling.md
Slow launchApp LaunchTime to first frame, pre-main, post-mainreferences/launch-optimization.md
Battery drainEnergy LogEnergy impact, CPU/GPU/network activityreferences/energy-diagnostics.md
Thermal issuesActivity Monitor, InstrumentsThermal state transitionsreferences/energy-diagnostics.md
Network wasteNetwork profilerRedundant fetches, payload sizereferences/energy-diagnostics.md

Workflow

  1. Identify the performance category from the user report, traces, logs, or code path.

  2. Read only the matching reference file unless the issue is broad or unclear.

  3. Prefer real device profiling with a Release build and representative data.

  4. Inspect the code path named by the profile before proposing a fix.

  5. Apply the smallest targeted fix that addresses the measured bottleneck.

  6. Re-profile or add a repeatable measurement to confirm the improvement.

Profiling Ground Rules

  • Profile on device when possible; Simulator uses host CPU and memory.

  • Use Release configuration because optimizations can change hot paths.

  • Reproduce with representative data, not empty databases or toy assets.

  • Close unrelated apps to reduce noise during profiling.

  • Keep measurements before and after the fix so the outcome is concrete.

  • Add os_signpost markers when a workflow needs ongoing timing visibility.

Xcode Diagnostics

Recommend relevant Scheme > Run > Diagnostics settings when they match the suspected issue:

SettingUse For
Main Thread CheckerUI work off the main thread
Thread SanitizerData races and unsafe shared state
Address SanitizerBuffer overflows and use-after-free
Malloc Stack LoggingAllocation call stacks
Zombie ObjectsMessages to deallocated objects

MetricKit Hook

Suggest MetricKit for production monitoring of launch, responsiveness, memory, and diagnostics:

import MetricKit

final class PerformanceReporter: NSObject, MXMetricManagerSubscriber {
    func startCollecting() {
        MXMetricManager.shared.add(self)
    }

    func didReceive(_ payloads: [MXMetricPayload]) {
        for payload in payloads {
            if let launch = payload.applicationLaunchMetrics {
                log("Resume time: \(launch.histogrammedResumeTime)")
            }
            if let responsiveness = payload.applicationResponsivenessMetrics {
                log("Hang time: \(responsiveness.histogrammedApplicationHangTime)")
            }
            if let memory = payload.memoryMetrics {
                log("Peak memory: \(memory.peakMemoryUsage)")
            }
        }
    }

    func didReceive(_ payloads: [MXDiagnosticPayload]) {
        for payload in payloads {
            if let hangs = payload.hangDiagnostics {
                for hang in hangs {
                    log("Hang: \(hang.callStackTree)")
                }
            }
        }
    }
}

Review Checklist

Responsiveness:

  • No synchronous work on the main thread over 100 ms.

  • No file I/O or network calls on the main thread.

  • Large Core Data or SwiftData fetches use background contexts.

  • Images decode off the main thread.

  • @MainActor is limited to code that truly needs UI access.

Memory:

  • No retain cycles in delegates, closures, observers, or async tasks.

  • Large resources are released when no longer visible.

  • Collections and caches are bounded.

  • autoreleasepool is used in tight loops that create Objective-C objects.

Launch:

  • No heavy work in init() of the @main App struct.

  • Non-essential initialization is deferred.

  • Dynamic frameworks are minimized where practical.

  • No synchronous network calls occur during launch.

Energy:

  • Background tasks use the appropriate BGTaskScheduler request type.

  • Location accuracy matches the product need.

  • Timers use tolerance so the system can coalesce wakeups.

  • Network requests are batched and cached where possible.

References

  • references/time-profiler.md: CPU profiling, hang detection, signpost API.

  • references/memory-profiling.md: Allocations, Leaks, Memory Graph debugger.

  • references/launch-optimization.md: Launch phases and cold/warm start optimization.

  • references/energy-diagnostics.md: Battery, thermal state, and network efficiency.

Files

references/time-profiler.md

Time Profiler & Hang Detection

Contents

  • Instruments Setup

  • Reading Time Profiler Results

  • Hang Detection

  • os_signpost API for Custom Profiling

  • Thread Performance Checker

  • Profiling Tips

Instruments Setup

Time Profiler Template
  1. Xcode > Product > Profile (Cmd+I) - builds Release and opens Instruments

  2. Choose Time Profiler template

  3. Click record, reproduce the slow operation, stop recording

Key Settings
  • Recording Mode: Deferred (lower overhead, recommended for production-like profiling)

  • High Frequency: 10ms sampling for fine-grained analysis (default is 1ms)

  • Record Waiting Threads: Enable to see threads blocked on locks/IO

Reading Time Profiler Results

Call Tree Navigation
  • Weight: Total time spent in function + all children

  • Self Weight: Time in just that function (no children)

  • Symbol Name: Function/method being sampled

Essential Filters
FilterPurpose
Separate by ThreadIsolate main thread from background
Invert Call TreeShow leaf functions first (where time is actually spent)
Hide System LibrariesFocus on your code
Flatten RecursionCollapse recursive calls into one entry
Typical Workflow
  1. Separate by Thread - find Main Thread

  2. Invert Call Tree - heaviest leaf functions appear at top

  3. Hide System Libraries - focus on your functions

  4. Click disclosure triangle to trace back through the call chain

  5. Double-click a function to jump to source code

Hang Detection

What Counts as a Hang
DurationClassificationUser Perception
< 100msAcceptableSmooth
100-250msMicro-hangSlight stutter
250ms-1sHangNoticeable delay
> 1sSevere hangApp feels broken
> 3sWatchdog kill riskSystem may terminate
Using the Hangs Instrument
  1. Open Instruments, choose Time Profiler (includes Hang detection lane)

  2. Or use standalone Animation Hitches instrument for UI-specific stalls

  3. Record and reproduce the interaction

  4. Orange/red regions in the Hangs lane indicate hang duration

  5. Click a hang to see the main thread call stack at that moment

Common Hang Causes and Fixes
Synchronous File I/O on Main Thread
// Bad - blocks main thread
func loadData() -> Data {
    return try! Data(contentsOf: largeFileURL)
}

// Good - move to background
func loadData() async -> Data {
    return try! await Task.detached {
        try Data(contentsOf: largeFileURL)
    }.value
}
Synchronous Network Call
// Bad - URLSession.shared.dataTask is async but
// this pattern blocks main thread waiting for result
let data = try! Data(contentsOf: remoteURL)

// Good - use async/await
let (data, _) = try await URLSession.shared.data(from: remoteURL)
Heavy Computation on Main Thread
// Bad - sorting/filtering large arrays on main thread
func updateUI() {
    let sorted = hugeArray.sorted { $0.score > $1.score }
    tableView.reloadData()
}

// Good - offload computation
func updateUI() async {
    let sorted = await Task.detached {
        hugeArray.sorted { $0.score > $1.score }
    }.value
    tableView.reloadData()
}
Core Data / SwiftData Fetch on Main Thread
// Bad - fetching thousands of objects blocks UI
let items = try context.fetch(FetchDescriptor<Item>())

// Good - use background context (SwiftData)
let items = try await Task.detached {
    let context = ModelContext(container)
    return try context.fetch(FetchDescriptor<Item>())
}.value
Image Decoding on Main Thread
// Bad - decoding happens lazily on first display, blocking main thread
imageView.image = UIImage(contentsOfFile: path)

// Good - decode off main thread (iOS 15+)
let thumbnail = await UIImage(contentsOfFile: path)?
    .byPreparingThumbnail(ofSize: targetSize)
imageView.image = thumbnail

// Good - using preparingForDisplay
let decoded = await UIImage(contentsOfFile: path)?
    .byPreparingForDisplay()

os_signpost API for Custom Profiling

Add signposts to measure specific operations in Instruments:

import os

extension OSSignpostID {
    static let dataLoad = OSSignpostID(log: .performance)
}

extension OSLog {
    static let performance = OSLog(
        subsystem: Bundle.main.bundleIdentifier!,
        category: "Performance"
    )
}

// Mark intervals
func loadData() async throws -> [Item] {
    let signpostID = OSSignpostID(log: .performance)
    os_signpost(.begin, log: .performance, name: "DataLoad", signpostID: signpostID)
    defer {
        os_signpost(.end, log: .performance, name: "DataLoad", signpostID: signpostID)
    }

    // ... actual work
    return items
}

// Mark events (single point)
os_signpost(.event, log: .performance, name: "CacheMiss")
Viewing Signposts in Instruments
  1. Add os_signpost instrument to your trace

  2. Filter by subsystem/category to find your markers

  3. Intervals show as bars with duration, events show as points

Thread Performance Checker

Enable in Scheme > Run > Diagnostics > Thread Performance Checker.

Detects at runtime:

  • Priority inversions: High-priority thread waiting on low-priority thread

  • Non-UI work on main thread: Disk I/O, network calls detected on main

  • Excessive thread creation: Spawning too many threads

Issues appear as purple runtime warnings in Xcode's Issue Navigator.

Profiling Tips

Profile What Matters
  • Always profile on physical device - Simulator has different CPU/memory characteristics

  • Use Release configuration - Debug builds disable compiler optimizations

  • Profile with realistic data - 10 items vs 10,000 items reveals different bottlenecks

  • Warm the app first - first run includes one-time setup that skews results

Interpreting Results
  • Focus on Self Weight to find actual bottlenecks (not just call tree weight)

  • A function with high weight but low self-weight is just a caller - dig deeper

  • Compare before/after traces to validate fixes

  • Look for repeated patterns - a function called 1000x at 1ms each = 1s hang

Quick Wins Checklist
  • [ ] Move all file I/O off main thread

  • [ ] Decode images asynchronously

  • [ ] Use @MainActor sparingly - only for actual UI updates

  • [ ] Batch database writes instead of single-row inserts

  • [ ] Cache expensive computations (JSON parsing, date formatting)

  • [ ] Use DateFormatter / NumberFormatter as shared instances (creation is expensive)

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
Meng To
Publisher
Meng To (Community)
Source
MengTo/Skills · agent-skills/codex/performance-profiling · commit 5ea1661
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Meng To or Meng To.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download performance-profiling.zip