Guides and Sample Code

Developer

Instruments User Guide

On This Page

Record, Pause, and Stop Traces

Instruments collects information about your app while it’s running. This chapter describes how to direct instruments to collect information.

Record a Trace

When you’re ready to profile your app, you initiate recording. While recording, the instruments in your trace document monitor your app based on their configurations. As recording occurs, the timeline pane and detail pane update to provide a live view of what’s being captured.

To begin recording

Do one of the following:

  • Click the Record button (image: ../Art/inline_record_button_2x.png) in the trace document toolbar.

  • Choose File > Record Trace (or press Command-R).

    image: ../Art/instruments_recordtrace_menu_2x.png

    Press Command-R again to stop recording.

Set Recording Options

Set recording options to improve data collection in a trace document. Choose a delay before recording, the length of time to record, the amount of data to save, or whether to record data in deferred mode.

To set the recording options for a trace
  1. Choose File > Record Options to open the Record Options dialog.

    image: ../Art/instruments_recordoptions_menu_2x.png
  2. Customize the settings as desired.

    image: ../Art/instruments_recordoptions_dialog_2x.png

    Options include:

    • Time limit: The maximum amount of time, in seconds, that the instruments will record data.

    • Window limit: The maximum duration, in seconds, of data that will be saved. If recording continues for longer than the time you specify as the window limit (for example, longer than 4 seconds), only the data collected during the last 4 seconds is saved.

    • Deferred mode: Select to defer data analysis until after data collection is complete. This can result in faster and more accurate data collection, as more system resources are directed at the process being recorded.

  3. Click OK to close the Record Options dialog.

Pause a Trace

If necessary, you can pause a recording and resume again at a later time.

To pause an active recording

Do one of the following:

  • Click the Pause button (image: ../Art/inline_pause_button_2x.png) in the trace document toolbar.

  • Choose File > Pause Trace (or press Shift-Command-R).

    image: ../Art/instruments_pausetrace_menu_2x.png

Stop a Trace

Once you’ve recorded the data you want, stop the recording so you can begin analyzing the collected data.

To stop an active recording

Do one of the following:

  • Click the Stop button (image: ../Art/inline_stop_button_2x.png) in the trace document toolbar.

  • Choose File > Stop Trace (or press Command-R).

    image: ../Art/instruments_stoptrace_menu_2x.png

Profile from the Dock

You can automatically record certain events in the background by triggering Time Profiler from the Instruments app icon in the Dock.

To collect Time Profiler information from the Dock
  1. With Instruments open, Control-click the Instruments icon in the Dock.

    image: ../Art/instruments_app_icon_small_2x.png
  2. From the shortcut menu that appears, choose the process to profile to start recording.

    image: ../Art/instruments_dock_menu_2x.png

    Options include:

    • System Time Profile. Starts profiling all system processes.

    • Time Profile Specific Process. Starts the Time Profiler instrument with a specific app from the submenu.

    • Automatically Time Profile Spinning Applications. Automatically profiles blocked (spinning) apps in the future.

    • Allow Tracing of Any Process (10 hours). Trace any process that occurs in the next 10 hours. Bypasses having to enter a password during the 10 hours.

Profile from Xcode

Instruments is a key component of the Xcode development workflow, and you can initiate it directly from within Xcode as you build and test your app.

Profile from the build and product menus

The Xcode build menu allows you to run, test, and analyze your app. It also allows you to profile your app with instruments.

To profile your app from the Xcode build and product menus
  1. Open an app project in Xcode.

  2. Do one of the following:

    • Click and hold the build menu in the Xcode main window, and choose Profile from the menu that appears.

      image: ../Art/xcode_toolbar_build_menu_profile_option_2x.png
    • Choose Product > Profile (or press Command-I).

      image: ../Art/xcode_product_menu_profile_menu_2x.png

    Instruments launches, and the profiling template selection dialog appears. Note that your app is automatically selected in the target device and process lists.

    image: ../Art/instruments_profiling_template_window_initiatedbyxcode_2x.png
To use a default template when profiling from the Xcode build and product menus
  1. Open an app project in Xcode.

  2. Open the scheme editor dialog by doing one of the following:

    • Select Edit Scheme from the target device list in the Xcode main window toolbar.

      image: ../Art/xcode_targetdevice_list_editscheme_option_2x.png
    • Choose Product > Scheme > Edit Scheme, or press Command–Less Than (<).

      image: ../Art/xcode_product_menu_editscheme_menu_2x.png
  3. Click Profile in the sidebar of the scheme editor dialog.

    image: ../Art/xcode_scheme_editor_dialog_sidebar_profile_option_2x.png
  4. From the Instrument pop-up menu, choose the desired profiling template.

    image: ../Art/xcode_scheme_editor_dialog_profile_option_instrument_popup_2x.png
  5. Click Close.

    Now, whenever you profile your app, Instruments automatically opens it in the template you selected in the scheme editor dialog and starts profiling.

    image: ../Art/instruments_activitymonitorprofilingfromxcode_2x.png

Profile from Xcode gauges while debugging

The Xcode debug navigator includes several gauges that monitor an app as you test and debug it. These gauges track a variety of factors, including CPU usage, memory, and energy impact, and can alert you to potential problems that may impact performance, power consumption, and more. If you identify a trend you wish to investigate further while testing your app, you can transition monitoring over to Instruments for more detailed analysis.

To initiate profiling from an Xcode gauge
  1. Open an app project in Xcode and run it.

  2. While your app is running, display the debug navigator by doing one of the following:

    • Click the Debug Navigator button in the navigator selector bar.

      image: ../Art/xcode_navigatorselector_bar_debugnaviagator_button_2x.png
    • Choose View > Navigators > Show Debug Navigator (or press Command-6).

      image: ../Art/xcode_view_menu_debugnavigator_menu_2x.png
  3. Click the desired gauge in the debug navigator.

    image: ../Art/xcode_debug_navigator_selectedgauge_2x.png
  4. Click the gauge’s Profile in Instruments button in the main editor.

    image: ../Art/xcode_gauge_profileininstruments_button_2x.png

    Note that not every Xcode gauge has a Profile in Instruments button. The Energy Impact gauge, for example, includes several buttons for initiating different types of profiling sessions in Instruments.

    image: ../Art/xcode_timeprofiler_gauge_profileininstruments_button_2x.png
  5. When prompted, select whether to transfer the currently running instance of your app over to Instruments or stop the app and start a new instance of it with Instruments.

    image: ../Art/xcode_profileininstrruments_alert_2x.png

    In both cases, note that Xcode stops profiling your app, launches Instruments, and initiates profiling. If you chose to transfer the session, Instruments begins profiling your app in its current state.

Profile from the Command Line

Profile with instruments

Use the instruments command-line tool (see instruments(1) Mac OS X Developer Tools Manual Page) to profile an app using a specified template without launching Instruments. Data gathered during profiling is saved in a .trace file into a specified directory. After profiling is complete, you can open the recorded data file with Instruments to see a visual representation of the data.

To profile with instruments
  1. Open Terminal, in /Applications/Utilities.

  2. Enter an instruments command to collect data.

    For example, the following command profiles an app with the Allocations template and saves the results to the desktop in a .trace file.

    • instruments -t "Allocations" -D ~/Desktop/
    • .trace
  3. Open Instruments, and choose File > Open.

    image: ../Art/instruments_fileopen_menu_2x.png
  4. Find your saved .trace file, and click Open.

    image: ../Art/instruments_opentracefile_dialog_2x.png

    After opening the saved file, Instruments automatically adds the associated instruments to a trace document and populates them with the collected data. You can view and analyze the data in order to locate any issues with your app.

    image: ../Art/instruments_loadedtrace_file_2x.png

instruments Options

instruments provides the following set of configuration options for defining what data to collect.

Configuration Option

Description

-t template

The name or path of the profiling template to use when analyzing your app.

-s

Returns a list of all installed profiling templates.

-D document

The path where the .trace document should be saved. If the file already exists, the newly recorded data is appended to it as a new run.

-l #

The amount of time to record, in milliseconds, before terminating. If not provided, recording occurs indefinitely, until the app is manually terminated.

-i #

The index of the instrument to use for recording.

-p pid

The process ID of the app to be recorded.

application

The path of the app to be recorded.

-w hardware device

The ID of the device to target.

-e variable value

An environment variable to be applied while profiling.

argument

A command-line argument to be passed to the app being profiled. Multiple arguments may be specified, if desired.

-v

Enables verbose logging while profiling.

Collect and view data with iprofiler

Use the iprofiler command-line tool (see iprofiler(1) Mac OS X Developer Tools Manual Page) to measure an app’s performance without launching Instruments. After collecting performance data, import it into Instruments in order to see a visual representation of the data. Data collected by iprofiler is saved in a .dtps bundle that can be opened by Instruments. iprofiler supports the following types of profiles:

  • Activity Monitor. Monitors overall system activity and statistics, including CPU, memory, disk, and network. Activity Monitor also monitors all existing processes and parent/child process hierarchies.

  • Allocations. Measures heap memory usage by tracking allocations, including specific object allocations by class. Allocations can also record virtual memory statistics by region.

  • Counters. Collect performance monitor counter events using time- or event-based sampling methods.

  • Event Profiler. Samples the processes running on the system’s CPUs through low-overhead, event-based sampling.

  • Leaks. Measures general memory usage, checks for leaked memory, and provides statistics on object allocations by class as well as memory address histories for all active allocations and leaked blocks.

  • System Trace. Provides comprehensive information about system behavior. System Trace shows when threads are scheduled and shows all their transitions from user code into system code through either system calls or memory operations.

  • Time Profiler. Performs low-overhead, time-based sampling of processes running on the system’s CPUs.

To collect and view data from iprofiler
  1. Open Terminal, in /Applications/Utilities.

  2. Enter an iprofiler command to collect data.

    For example, the following command performs an Activity Monitor trace on your app for 5 seconds and saves the results to the desktop in a .dtps file.

    • iprofiler -activitymonitor -T 5s -d ~/Desktop/
  3. Open Instruments, and choose File > Open.

    image: ../Art/instruments_fileopen_menu_2x.png
  4. Find your saved .dtps file, and click Open.

    image: ../Art/instruments_opendtpsfile_dialog_2x.png

    After opening the saved file, Instruments automatically adds the associated instruments to a trace document and populates them with the collected data. You can view and analyze the data in order to locate any issues with your app.

    image: ../Art/instruments_loadeddtps_file_2x.png

iprofiler Options

iprofiler provides the following set of configuration options for defining what data to collect.

Configuration Option

Description

-l

Provides a list of all supported instruments.

-L

Provides a list of all supported instruments and a description of what each template does.

-legacy

Executes the legacy Instruments command-line interface found in /usr/bin/instruments.

-T duration

Sets the length of time for which data is collected. Set duration in seconds (ns or n), milliseconds (nm or nms), or microseconds (nu or nus). The default is 10 seconds.

-I interval

Sets the frequency with which a measurement is taken during the sample time. Set the interval to seconds (ns or n), milliseconds (nm or nms), or microseconds (nu or nus). The default is the Instruments app’s default sampling interval.

-window period

Limits the performance measurement to the final period of the iprofiler run. Set the period to seconds (ns or n), milliseconds (nm or nms), or microseconds (nu or nus). If this option is not specified, performance is measured throughout the entire run.

Note: This option can be used only with the -timeprofiler and -systemtrace template options.

-d path -o basename

Specifies the destination path and the name used when saving the collected data. The default path is the current working directory. The default basename is the process name or process ID.

-instrument name

Designates the instrument to be run. Valid name options are -activitymonitor, -allocations, -counters, -eventprofiler, -leaks, -systemtrace, and -timeprofiler.

At least one template must be listed. You can run up to all seven templates at once.

-kernelstacks

Designates kernel stacks only for backtraces.

If neither -kernelstacks nor -userandkernelstacks options are specified, backtraces include user stacks only.

-userandkernelstacks

Designates both kernel and user stacks for backtraces.

If neither -kernelstacks nor -userandkernelstacks options are specified, backtraces include user stacks only.

-pmc PMC_MNEMONIC

When used with -counters, specifies the mnemonic of the event to count. Multiple mnemonics should be comma-separated.

-allthreadstates

Causes the Time Profiler template to profile all threads. If this value is not specified, Time Profiler profiles only running threads.

-a process/pid

Attaches to a process that is already running. Specifying a string attaches the process whose name starts with that string. Specifying a process ID attaches it to the process associated with that process ID.

The -leaks option requires you to specify a specific single process or process ID.

executable [args…]

Causes the target process to be launched for the duration of the measurement. Lists the executable and the arguments as if they are being invoked from the command line.

iprofiler Examples

A list of common iprofiler command-line examples are below.

This example collects data from all running processes for the current sampling duration set in Instruments using the Time Profiler and Activity Monitor instruments. The collected data is saved to the working directory as allprocs.dtps.

  1. iprofiler -timeprofiler -activitymonitor

The following example opens and collects data from YourApp using the Time Profiler instrument. Data is collected for eight seconds, and the data is saved at /temp/YourApp_perf.dtps.

  1. iprofiler -T 8s -d /temp -o YourApp_perf -timeprofiler -a YourApp

The following example collects data from the process with the 823 process ID using the Leaks and Activity Monitor instruments. Data is collected for 2500 milliseconds (2.5 seconds) and is saved to the working directory as YourApp_perf.dtps.

  1. iprofiler -T 2500ms -o YourApp_perf -leaks -activitymonitor -a 823

The following example opens and collects data from YourApp using the Time Profiler and Allocations instruments. Data is collected for the default amount of time set in Instruments and saved in /tmp/allprocs.dtps.

  1. iprofiler -d /tmp -timeprofiler -allocations -a YourApp.app

The following example opens and collects data from YourApp found in /path/to with the argument arg1 using the Time Profiler and System Trace instruments. Data is collected for 15 seconds, but only the data collected in the last 2 seconds is saved. The data is saved to the working directory as YourApp_perf.dtps.

  1. iprofiler -T 15 -I 1000ms -window 2s -o YourApp_perf -timeprofiler -systemtrace /path/to/Your.app arg1

Minimize Instruments Impact on Data Collection

Instruments is designed to minimize its own impact on data collection. By changing some basic settings, however, you can further decrease the impact Instruments has on data collection.

You can decrease the sample interval for many instruments in order to collect more data. However, high sample rates that result from a short sample interval can cause several problems:

  • Processor time is required for every sample. High sample rates use more processor time.

  • Sample interval timing may not be consistent. Interrupts are used to start each sample. Variations in when these interrupts occur can cause significant variations in the sample rate when using very small sample intervals.

  • Small sample intervals cause more samples to be taken. Each sample uses system memory, and a large number of samples quickly uses up the available memory on machines with less memory.

Run Instruments in Deferred Mode

Increase the accuracy of performance-related data by deferring data analysis until you quit the app you are testing. Typically, Instruments analyzes and displays data while your app runs, allowing you to view the data as it is collected. Performing analysis live slows down the target process by taking up CPU time and memory, which leaves you with measurements that may not reflect how the process would normally behave. Running Instruments in deferred mode delays the analysis of data until the data collection is done, either after your app has finished running or after you click Stop. While in deferred mode, you are blocked from interacting with the instruments that are collecting data.

In deferred mode, after Instruments finishes collecting data, Instruments processes the data and displays it onscreen. Deferring data analysis adds time to the later stages of the data collection process, but it helps ensure that performance-related data is accurate.

To set deferred mode for Instruments
  1. Choose Instruments > Preferences.

    image: ../Art/instruments_preferences_menu_2x.png
  2. In the Recording pane, select the “Always use deferred mode” checkbox.

    image: ../Art/instruments_prefs_recording_deferred_option_2x.png

For especially long traces, the delay caused by deferred mode can be significant. Avoid this delay by setting deferred mode for only those traces that require extremely precise data collection.

To set deferred mode for a trace
  1. Choose File > Record Options.

    image: ../Art/instruments_recordoptions_menu_2x.png
  2. In the dialog that appears, select the Deferred Mode checkbox and then click OK.

    image: ../Art/instruments_recordoptions_dialog_deferred_option_2x.png

    This option is disabled if “Always use deferred mode” is enabled in Instruments preferences.