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://mp-staging.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/launch-optimization.md

Launch Time Optimization

Contents

  • App Launch Phases

  • App Launch Instrument

  • Pre-main Optimization

  • Post-main Optimization

  • Measuring Launch Time in Code

  • MetricKit Launch Metrics

  • Launch Optimization Checklist

App Launch Phases

Cold Launch Timeline
--------------------------------------------------------
|  Pre-main                |  Post-main               |
|                          |                           |
|  DYLD        Runtime     |  App Init    First Frame  |
|  loading     init        |  UIKit/SwiftUI setup      |
|  ----------  ----------  |  ------------  ----------  |
|  dylibs      +load       |  AppDelegate   viewDidLoad|
|  rebasing    static      |  @main App     .body      |
|  binding     initializers|  scene setup   layout     |
|              ObjC setup  |  root view     render     |
--------------------------------------------------------
                                              ^
                                    First Frame Rendered
                                    (launch complete)
Target Budgets
Launch TypeGoodAcceptablePoor
Cold launch< 400ms< 1s> 2s
Warm launch< 200ms< 500ms> 1s
Resume< 100ms< 200ms> 500ms

Cold launch: App not in memory - full DYLD load, runtime init, UI setup. Warm launch: App recently terminated but system cached some data. Resume: App was suspended in background.

App Launch Instrument

Setup
  1. Xcode > Product > Profile (Cmd+I)

  2. Choose App Launch template

  3. Record - the app launches and Instruments captures the entire timeline

  4. Stop after app is fully interactive

Reading the Results
  • Process Lifecycle lane shows app state transitions

  • Thread State lane shows main thread activity during launch

  • Time Profiler lane shows CPU work during launch

  • Focus on the region between process start and first frame

Key Measurements
  • Time to first frame: Total duration from process start to first CA commit

  • Pre-main time: From process start to main() / @main entry

  • Post-main time: From main() to first frame rendered

Pre-main Optimization

Reduce Dynamic Frameworks

Each dynamic framework adds ~10-30ms to launch:

Before: 15 dynamic frameworks -> ~300ms DYLD loading
After:  3 dynamic frameworks  -> ~50ms DYLD loading

How to fix:

  • Convert dynamic frameworks to static libraries where possible

  • Use Swift Package Manager (static by default) instead of dynamic frameworks

  • Merge small frameworks into fewer larger ones

  • Check with: otool -L YourApp.app/YourApp to list linked dylibs

Remove Static Initializers

Static initializers (+load, __attribute__((constructor))) run before main():

// Bad - runs before main(), delays launch
class LegacyManager: NSObject {
    override class func load() { // ObjC +load
        setup()
    }
}

// Bad - C-style constructor
@_cdecl("initEarly")
func initEarly() { /* runs before main */ }

// Good - defer to first use
class LegacyManager {
    static let shared = LegacyManager() // Lazy, created on first access
}
Minimize ObjC Metadata
  • Large ObjC class hierarchies increase rebasing/binding time

  • Swift classes without @objc are more efficient

  • Reduce ObjC category usage (each category adds metadata)

Post-main Optimization

Defer Non-Essential Initialization
@main
struct MyApp: App {
    init() {
        // Bad - all of this delays first frame
        AnalyticsManager.shared.configure()
        CrashReporter.shared.start()
        RemoteConfig.shared.fetch()
        ImageCache.shared.warmUp()
        DatabaseMigrator.run()
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

// Good - only essential work at init, defer the rest
@main
struct MyApp: App {
    init() {
        // Only crash reporter is truly needed immediately
        CrashReporter.shared.start()
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
                .task {
                    // Defer everything else to after first frame
                    await deferredSetup()
                }
        }
    }

    private func deferredSetup() async {
        AnalyticsManager.shared.configure()
        RemoteConfig.shared.fetch()
        ImageCache.shared.warmUp()
    }
}
Lazy View Loading
// Bad - all tabs initialize their full view hierarchy at launch
TabView {
    HomeView()        // Heavy: fetches data, builds complex layout
    SearchView()      // Heavy: initializes search index
    ProfileView()     // Heavy: loads user data
}

// Good - use lazy containers, each tab builds only when selected
TabView {
    NavigationStack {
        HomeView()
    }
    .tabItem { Label("Home", systemImage: "house") }

    NavigationStack {
        SearchView()
    }
    .tabItem { Label("Search", systemImage: "magnifyingglass") }
}
// SwiftUI NavigationStack already lazy-loads destination views
// For custom containers, use LazyVStack instead of VStack
Reduce Initial View Complexity
// Bad - loading everything at once
struct ContentView: View {
    @State private var allItems: [Item] = []

    var body: some View {
        List(allItems) { item in
            ComplexItemView(item: item)
        }
        .onAppear {
            allItems = try! ModelContext(container).fetch(
                FetchDescriptor<Item>(sortBy: [SortDescriptor(\.date)])
            )
        }
    }
}

// Good - show skeleton immediately, load data async
struct ContentView: View {
    @State private var items: [Item]?

    var body: some View {
        Group {
            if let items {
                List(items) { item in
                    ItemRow(item: item)
                }
            } else {
                SkeletonListView() // Lightweight placeholder
            }
        }
        .task {
            items = await loadItems()
        }
    }
}
Database Migration at Launch
// Bad - blocking migration on main thread
let container = try ModelContainer(for: Item.self)
// If migration runs, this blocks until complete

// Good - show migration UI if needed
struct AppEntry: View {
    @State private var container: ModelContainer?
    @State private var isMigrating = false

    var body: some View {
        Group {
            if let container {
                ContentView()
                    .modelContainer(container)
            } else if isMigrating {
                MigrationProgressView()
            } else {
                ProgressView()
            }
        }
        .task {
            await setupContainer()
        }
    }

    private func setupContainer() async {
        // Check if migration needed
        if await needsMigration() {
            isMigrating = true
        }
        container = try? await Task.detached {
            try ModelContainer(for: Item.self)
        }.value
        isMigrating = false
    }
}

Measuring Launch Time in Code

Using os_signpost
import os

@main
struct MyApp: App {
    static let launchLog = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "Launch")
    static let launchSignpost = OSSignpostID(log: launchLog)

    init() {
        os_signpost(.begin, log: Self.launchLog, name: "AppLaunch", signpostID: Self.launchSignpost)
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
                .onAppear {
                    os_signpost(.end, log: Self.launchLog, name: "AppLaunch", signpostID: Self.launchSignpost)
                }
        }
    }
}
Using CFAbsoluteTimeGetCurrent
// Quick and dirty launch measurement
@main
struct MyApp: App {
    static let launchStart = CFAbsoluteTimeGetCurrent()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .onAppear {
                    let elapsed = CFAbsoluteTimeGetCurrent() - Self.launchStart
                    print("Launch time: \(String(format: "%.3f", elapsed))s")
                }
        }
    }
}

MetricKit Launch Metrics

Production launch time data from real users:

func didReceive(_ payloads: [MXMetricPayload]) {
    for payload in payloads {
        if let launch = payload.applicationLaunchMetrics {
            // Histogram of time-to-first-draw
            let histogram = launch.histogrammedTimeToFirstDraw
            for bucket in histogram.bucketEnumerator {
                guard let bucket = bucket as? MXHistogramBucket<UnitDuration> else { continue }
                print("[\(bucket.bucketStart) - \(bucket.bucketEnd)]: \(bucket.bucketCount) launches")
            }

            // Resume time histogram
            let resumeHistogram = launch.histogrammedResumeTime
            // Same enumeration pattern
        }
    }
}

Launch Optimization Checklist

Pre-main
  • [ ] Minimize dynamic frameworks (prefer static linking)

  • [ ] No +load methods or static initializers

  • [ ] Remove unused frameworks from Link Binary With Libraries

  • [ ] Strip unused architectures in release builds

Post-main (App Init)
  • [ ] Only essential setup in App.init() or AppDelegate (crash reporter only)

  • [ ] Analytics, remote config, and prefetch deferred to .task {} after first frame

  • [ ] No synchronous network calls at launch

  • [ ] No blocking database migrations on main thread

First Frame
  • [ ] Initial view is lightweight (skeleton/placeholder)

  • [ ] Data loading is async with .task {}

  • [ ] Heavy views (maps, web views, complex lists) lazy-loaded

  • [ ] Images use thumbnails, not full resolution

Verification
  • [ ] Measure with App Launch Instrument on oldest supported device

  • [ ] Cold launch < 400ms on target device

  • [ ] No regressions after changes (compare Instruments traces)

  • [ ] MetricKit showing stable or improving launch times in production

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.

Download ZIP

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