When you ’ re done, either leave the trace document window open, save it, or close asyou wish.. Start the application from Xcode again, using the same Instruments template.. More Detail
Trang 1Learn More About Shark
This introduction to Shark only scratches its surface Full documentation for Shark is availablewithin the application itself in the Help menu There is a user ’ s guide, profi ling and data miningtutorials, as well as interactive processor instruction references
Shark can analyze multiple processes and applications that are no longer responding You can startand stop its sampling from within your application, the keyboard, or using command - line tools
It can debug memory bandwidth issues, processor cache hits, and virtual memory paging Readthe documentation for a complete description of all of these features If you still have questions,consider joining the Performance Analysis and Optimization mailing list (PerfOptimization - dev) at
http://lists.apple.com/
INSTRUMENTS
Instruments is an application for doing performance analysis Instruments replaces a hodgepodgecollection of older utilities (Sampler, Big Top, Spin Control, ObjectAlloc, Thread Viewer, andothers) with a uniform, fl exible, and coordinated set of modular testing tools Using Instruments,you can quickly assemble a custom set of analysis modules that will target, and hopefullyilluminate, exactly the problem you ’ re trying to solve
To use Instruments, you assemble a deck of customized data collection modules (called instruments )
that gather information about your application, the entire system, or both The arrangement,
as shown in Figure 19 - 8, comes out looking something like Garage Band Each track records adifferent aspect of your application or the system You can examine the details of an individualtrack, correlate different tracks, replay your application ’ s performance, compare the performance ofdifferent runs, and much more
Trang 2526 ❘CHAPTER 19 PERFORMANCE ANALYSIS
The Instruments User Guide is quite good You can fi nd it by searching for “ Instruments ” in the
Xcode documentation or online at http://developer.apple.com/mac/library/documentation/
DeveloperTools/Conceptual/InstrumentsUserGuide/ The user guide, however, focuses mostly
on what Instruments can do and how to use it as a standalone application This chapter focuses
more on how to use Instruments in an Xcode workfl ow, and demonstrates using Instruments to solve
some typical development problems The two are complementary, and I encourage you to read both
Terminology
The following table defi nes the vocabulary used by Instruments:
Recording Trace Data
Running your application under the watchful gaze of Instruments is very simple:
1. Build your application (Command+B)
2. Choose an Instruments template from the Run ➪ Run With Performance Tool menu
The fi rst step is important None of the commands that start performance analysis builds your
project fi rst, so if you ’ ve made changes and want to test those changes, build your project fi rst
Xcode launches Instruments in the correct mode for your target application, confi gures it using the
selected template, and starts your application running
Not all Instruments templates are available for every target For example, iPhone OS 3.0 does not
provide garbage collection, so the GC Monitor template is grayed out for iPhone apps Here ’ s a list of
the more popular Xcode - supplied templates and the kinds of issues you would use them to analyze:
possibly ones that cause excessive
VM memory usage
memory leaks
Trang 3XCODE INSTRUMENTS TEMPL ATE INSTRUMENTS USE
with overall system CPU utilization
and state history
Central Dispatch queues lookingfor CPU utilization, bottlenecks, andstalls
ObjectAlloc, GarbageCollection
Look at the high - level picture ofobject allocation, lifespan, andgarbage collection activity
Writes, File Attributes,Directory I/O
A combination of instrumentsthat monitor all high - level fi leactivity Use it to look for fi leaccess problems, ordering, orineffi cient I/O
Data Cache Misses, CoreData Saves
Track down poor Core Dataperformance looking for excessivefetches, poor caching, or slow saves
Instrument collection continues as long as the application is running Quitting your application,
or pressing the Stop button in Instruments, terminates data collection — and yourapplication
Instruments ’ interface is live You can browse, dig into, and analyze data as it’s beingcollected When you ’ re done, either leave the trace document window open, save it, or close asyou wish
Be careful of trying to do too much in Instruments while simultaneously gathering instrument data that involves system resources, like the CPU Sampler
or Multicore templates Instruments is, itself, using CPU, memory, and fi le system services to do its job This can skew the results of your application ’ s performance
Trang 4528 ❘CHAPTER 19 PERFORMANCE ANALYSIS
Accumulating and Discarding Traces
After terminating your test application, leave the trace document open and do one of two things:
Press the Record button to restart the application
Start the application from Xcode again, using the same Instruments template
Instruments will, again, start your application and begin recording The recording creates a
second data set, called a run , in the trace document Every time you restart your application in
the same trace document, Instruments accumulates another run Figure 19 - 9 shows four instruments
with three runs of accumulated data
current run is always shown on the instrument ’ s main track
You can also page through the runs using the time control in the toolbar Click the arrows to select
the current run This run becomes the data that appears in the main track of every instrument
Use the run selector to review the entire results of a previous run
➤
➤
Trang 5Run data can consume a lot of fi le, memory, and screen space If you have a run that you don ’ t fi ndinteresting anymore, make it the current run using the time control and then choose Instrument ➪Delete Run N Instruments will delete the n th run of samples from all instruments
The Run Browser
Another way to review multiple runs of analysis data is to use the run browser, shown in Figure 19 - 10
FIGURE 19-10
The run browser presents a cover fl ow style display of each run of instruments, along with somesummary information Here you can make comments about each run, delete a run, or click PromoteRun to switch immediately to that run in the trace document window — equivalent to using the runselector
The return button, at the lower right, returns you to the trace document window
Analyzing Trace Data
The data gathered from each instrument is organized into panes of successively more detailedinformation You start by perusing the tracks, which compactly summarize the data gathered
by that instrument To examine the data of a single instrument in more detail, select the trackand expand the details pane The details pane typically provides numerous fi lter, analysis, andexploration tools The details of individual samples can be explored even further in the extendeddetails pane Each of these is described in the following sections
Trang 6530 ❘CHAPTER 19 PERFORMANCE ANALYSIS
Tracks
Tracks present a graphical summary of the trace data for each instrument What information is
displayed, and how, is controlled by the inspector tab of the instrument You get to the inspector tab
by clicking the small i button at the right edge of each instrument, or by choosing File ➪ Get Info,
as shown on the left in Figure 19 - 11
Playhead
FIGURE 19-11
The inspector for each instrument varies, but in general you can choose the target (normally all
instruments target the same process, but that ’ s not a requirement), various instrument - specifi c
settings, and the format of the track ’ s graph The Style and Type controls determine what metric is
displayed in the track and how it ’ s drawn
The Zoom control increases or decreases the vertical size of the track, setting the resolution of
the graph You can also zoom the scale of the selected track using the View ➪ Increase Deck Size
(Command++) and View ➪ Decrease Deck Size (Command+ − ) commands
The Zoom control at the bottom of the window determines the horizontal magnifi cation of all of
the tracks Use the two zoom controls to zoom in on details, or zoom out to look for overall trends
You can peek at individual data points in the graph using the playhead control, as shown on the
right in Figure 19 - 11 When you drag the playhead control across the track, datatips show the values
of the data points in each track at that specifi c time Depending on the horizontal zoom, a single
pixel might represent several samples You may have to zoom in to review discrete data points
More Detail
After you ’ ve narrowed down the region of sample data you want to explore, it ’ s time to use the
details pane that appears at the bottom of the trace document window, as shown in Figure 19 - 12
The details pane is normally already visible by default, but you can collapse and expand it using the details
button in the lower - left corner of the window, or by choosing the View ➪ Detail (Command+D)
command
Trang 7Each instrument has its own details pane format, but generally it displays a tabular view of theinstrument ’ s individual samples and a structured view of its analysis It may alternatively presentgraphs, other organizations of the same data, console messages, or even the source code associatedwith the samples Each view is selected using the icons at the bottom of the details pane
If you ’ re trying to fi nd something specifi c, enter a search term in the search fi eld The term might be
a symbol name, address, or library name, depending on the type of information displayed You canusually narrow the scope of the search using the search fi eld ’ s menu
Even More Detail
When the detail in the details pane isn ’ t enough, you may need to open up the extended detailspane either by clicking the extended details view button to the right of the other detail views, or bychoosing the View ➪ Extended Detail (Command+E) command from the menu The extended detailpane appears on the right side of the trace document window, as shown in Figure 19 - 13
FIGURE 19-12
FIGURE 19-13
Trang 8532 ❘ CHAPTER 19 PERFORMANCE ANALYSIS
The extended details pane is about as close as you ’ re going to get to the raw data collected by the
instrument Samples may include a variety of information, depending on the instrument and how
it ’ s confi gured Some instruments don ’ t show any extended detail at all Three types of extended
data are very common:
of the simple properties of each sample This might include theaddress of the object, the fi le system function called, the size of thememory allocation, the entity name that caused the cache miss, and
so on
The stack trace group shows state of the call stack when that samplewas taken
timestamp group
Right/Control+clicking the stack trace presents a confi guration menu, shown on the right in
Figure 19 - 13, where you can :
Change the order in which stack frames are listed Color the functions by library
Choose how much information about each stack frame function is displayedJump to the API documentation for a function
Timeline
The timeline, shown in Figure 19 - 14, shows the temporal relationship of events in the tracks You
can use the timeline to :
Peek at data points in a track Jump to samples at a particular timeMark locations with a fl ag
Navigate between fl ags View and analyze a subset of the trace data
Trang 9Peeking and Navigating Using the Playhead
You ’ ve already seen how you can peek at data points in the track by dragging the playhead to a time
In detail views that list data points by sample/time, the playhead and the detail list are usually synchronized; dragging the playhead to a time selects that sample in the details pane, and selecting a sample in the details pane moves the playhead to that location in the timeline
Using Flags
You can mark interesting locations in the timeline using fl ags Flags are set and removed at the current playhead location, and you can jump the playhead to a previously set fl ag You can do this using the fl ag controls in the toolbar, or with the following commands:
Edit ➪ Add Flag (Command - ↓ ) Edit ➪ Remove Flag (Command - ↑ ) View ➪ Next Flag (Command - → ) View ➪ Previous Flag (Command - ← ) View ➪ Inspect Flag
The Next and Previous commands jump the playhead to the next or previous fl ag in the timeline The Inspect Flag command opens an inspector panel that allows you to name the fl ag and record comments for future reference, as shown in Figure 19 - 15
Flags
FIGURE 19-14
FIGURE 19-15
Trang 10534 ❘CHAPTER 19 PERFORMANCE ANALYSIS
Setting the Inspection Range
Normally, instruments present and analyze all of the data in a run If you ’ re interested in only
a portion of that data — specifi cally, just the samples between two events — you can set the
inspection range of the instruments using the Inspection Range controls in the toolbar To set
an inspection range:
1. Move the playhead to the fi rst sample to include in the analysis
2. Click the left button in the Inspection Range control
3. Move the playhead to the last sample to include
4. Click the right button in the Inspection Range control
All of the details and analysis performed by all instruments will now be constrained to just the data
collected between those two time periods, also shown in Figure 19 - 14
To reset the inspection range to include all samples again, click the center button in the Inspection
Range control
Sample numbers are relative That is, sample 0 is the fi rst sample in its data set When you change the inspection range, you change the sample data set and sample 0 will be the fi rst sample in the new range If you ’ re using the sample number to identify a data point, remember that its number will change if you alter the inspection range Also note that while sample numbers change, time stamps don ’ t
Customizing Instruments
Instruments can be customized in a myriad of ways Most instruments are customized through their
inspector pane, which you ’ ve already seen Other analysis and view settings are usually found in the
details pane containing the instrument ’ s data
When you edit instrument or display settings, those settings are part of the trace document Settings
are preserved when you save a trace document or continue to use a modifi ed trace document for
future runs
Using Instruments via Xcode adds a wrinkle to changing instrument settings When you launch
Instruments from Xcode you do so by selecting a template Normally, this creates a new trace
document and initiates a recording However, if Instruments already has a trace document open
and that document was created with the same template selected in Xcode, Instruments will reuse
the open document and accumulate another run Thus, as long as you continue to select the same
Instruments template in Xcode, Instruments will continue adding runs to the same trace document
Choose a different template and Instruments will create a new document — bypassing any changes
you ’ ve made to instrument settings
This has implications if you customize your instruments or trace document after starting
Instruments for the fi rst time To customize instruments in an Xcode workfl ow, use one of the
following workfl ows:
Trang 11Start Instruments using an Xcode template Customize the instruments and leave the trace
document open Start Instruments again from Xcode using the same template Instruments
will reuse the already open trace document and accumulate another run using thecustomized settings
Start Instruments using an Xcode template Customize the instruments and leave the tracedocument open Start another recording by clicking the Record button in Instruments orchoosing File ➪ Record Trace (Command+R) Instruments restarts your application andbegins recording This works as long as the location and run time environment of your testapplication remains unchanged — that is, you don ’ t change build confi gurations
Create a trace document (through any means), customize the instruments, and then save it
as a new Instruments template See the section “ Creating Instrument Templates ” later onfor the details Use the newly created template for future analysis
Trang 12536 ❘CHAPTER 19 PERFORMANCE ANALYSIS
Be frugal when adding instruments Instruments can gather a tremendous amount of data in a very short period of time — you can quickly overwhelm your computer system with too much data I have personally created (what
I thought was) a simple instrument set that within 30 seconds had ballooned the Instruments process to 56 gigabytes of virtual memory Even on a machine with 16 gigabytes of physical RAM, the data set was tediously slow to work with.
My time would have probably been better spent developing a more targeted analysis
Removing Instruments
Removing an instrument couldn ’ t be easier; select an instrument and choose the Instrument ➪
Delete Instrument command or press the Delete key
Removing an instrument removes it and all the data associated with that instrument If you want to
refer to the data for that instrument, consider saving the trace document fi rst or exporting the data
to a fi le
Saving and Exporting Instrument Data
All of your instruments, instrument settings, and trace data is stored in the trace document;
save and open trace documents like you would any other document type You can also export
trace data as a text fi le for external analysis, import trace data, and create your own instrument
templates
Trace data from many (but not all) instruments can be exported to a comma - separated value (CSV)
fi le This is a simple, common, text fi le format that is easy to parse and is compatible with most
spreadsheet and data analysis applications
Select the desired instrument and the set the current run to the data set you want to export Choose
the Instrument ➪ Export Track For ‘ Instrument ’ command
Creating Instrument Templates
Creating sets of instruments with just the right settings can be a lot of work — work you don ’ t want
to have to repeat every time you start a new analysis session One way to preserve that work is to
save a deck of confi gured instruments as an Instruments template
Creating the template is easy: set up a trace document with the instruments and settings you want
Choose the File ➪ Save As Template command and choose a location, description, and icon, as
shown in Figure 19 - 17 Opening that template document creates a new trace document with your
preconfi gured set of instruments