共用方式為


Performance Profiling Tools for WPF

WPF provides a suite of performance profiling tools that allow you to analyze the run-time behavior of your application and determine the types of performance optimizations you can apply. The following table lists the five performance profiling tools that are included in the Windows SDK tool, WPFPerf:

Tool Description

Event Trace

Use for analyzing events and generating event log files.

Perforator

Use for analyzing rendering behavior.

ETW Trace Viewer

Record, display, and browse Event Tracing for Windows (ETW) log files in a WPF user-interface format.

Visual Profiler

Use for profiling the use of WPF services, such as layout and event handling, by elements in the visual tree[Glossary Lookup Failure: visual_tree#484ef710-6484-400c-832c-768cb3a33aa5].

Working Set Analyzer

Use for analyzing the working set characteristics of your application.

This topic contains the following sections.

  • Using Performance Profiling Tools
  • Event Trace
  • Perforator
  • ETW Trace Viewer
  • Visual Profiler
  • Working Set Analyzer
  • Other Performance Tool Resources
  • Related Topics

Using Performance Profiling Tools

To run the performance profiling tools for WPF, select the Tools submenu from the Microsoft Windows SDK menu. Run the WpfPerf application in the Tools submenu. The first time you run WpfPerf, its host container window displays no tools. To add a tool to WpfPerf, click the plus sign on the tabbed window. The Add Tool dialog box appears:


Add Tool dialog box

Add Tool dialog box

NoteNote:

In order to use the performance profiling tools, your user account must be running with administrative access.

Event Trace

Event Tracing for Windows (ETW) is an efficient kernel-level tracing facility that lets you log kernel or application-defined events to a log file. You can consume the events in real time or from a log file and use them to debug an application or to determine where performance issues are occurring in the application. The WPF Event Trace profiling tool uses ETW for event logging. For more information on ETW, see Event Tracing.

Using Event Trace

The Event Trace main window displays a set of options that allow you to add, save, and view event logging information:


Event Trace main window

Event Trace main window

Adding a New Event Logger

To add a new event logger, click the Add button from the Event Trace main window. The Add New Logger dialog box displays a set of information for you to define. The Logger Name refers to the user-friendly name of the logger. Select one of the four types of event loggers from the dropdown list box that is labeled GUID:

  • NT Kernel Logger

  • Common Language Runtime Garbage Collection

  • Windows Presentation Foundation - Performance Only

  • Windows Presentation Foundation -All

There are two types of WPF event loggers. The "Performance Only" version is a reduced subset of the "All" version. The Log File allows you define the filename for the event log file. Click the button labeled "…" to define the filename. Event log files use the default file extension, "etl".

The Level option refers to the following severity levels that you can use. Higher numbers imply that you get lower levels as well. For example, if you specify 3, you also receive all warning, error, and fatal events:

Level Description

1

Abnormal exit or termination events.

2

Severe error events.

3

Warning events such as allocation failures.

4

Non-error events such as entry or exit events.

5

Detailed trace events.

The Flags option specifies the class of WPF events. In most cases, the default value is sufficient.

When you have finished creating the new event logging information, click the Add button of the Add New Logger dialog box to add the logger to Event Trace. You can create additional event loggers and add them to Event Trace. When you have finished adding all the event loggers, click the Done button.


Add New Logger dialog box

Add New Logger dialog box

To remove a specific event logger, select the event logger in list box and click the Remove button. To remove all event loggers, click the Clear button.

Enabling Event Logging

Select the event logger from the list of event loggers in the Event Trace main window. Click the Start button to enable logging. The status for the event logger should display Enabled.


Event Trace main window with an event logger selected

Event Trace main window with event loggers

When you have finished logging the events for your application, click the Stop button. To ensure that you have captured event logging information, you may want to view the event log file. Click the Open Log button to view the event log file.


Event Trace main window with event log information

Event Trace main window with event logging info

The event log file lists five columns of information for each event.

Column Description

Time

Current time in CPU ticks.

Guid

GUID corresponding to the event.

Name

Event name.

Event type

Info, Start, or End event. A Start event has a matching End event.

Data

Data related to a specific event type.

The event log information is not very useful in this format. Use the WPF ETW Trace Viewer profiling tool to analyze the output of an event log file created with Event Trace.

Perforator

Perforator is a performance profiling tool for analyzing rendering behavior. The Perforator main window displays a set of options that allow you to analyze very specific rendering behavior in parts of your application.


Perforator main window

Perforator main window

Perforator allows you to set a number of options that affect the real-time rendering behavior of the application:

Option Description

Draw software rendering with purple tint

Draws all areas rendered using the software rendering pipeline with a purple tint. This includes software render targets, software 3D content, and per-primitive software fallback.

Clear back-buffer before updating

Clears application windows before each drawing operation.

Show dirty region update overlay

Causes each update WPF makes to the screen to be indicated by re-coloring. This allows you to see when and where areas are redrawn in an application.

Disable dirty region support

Causes WPF to redraw the entire window anytime a change is made. Normally, only the portion of the window that has changed is redrawn. Enabling this option causes your application to render much more slowly.

Disable Opacity effects

Disables certain potentially performance-intensive uses of opacity.

Disable per-primitive software fallback

Disables software fallback for individual rendering primitives. Software intermediate render targets and other software rendering cannot be disabled.

Disable high-quality image rescaling

Disables the rescaling of large images to smaller sizes.

Disable 3D rendering

Disables all 3D rendering operations

Enable Debug Control Option

The Enable Debug Control checkbox allows you to enable or disable access to WPF shared memory. By default, Perforator enables this option on startup, and disables this option on termination. In the event of an abnormal termination of Perforator, restart it and manually uncheck the Enable Debug Control checkbox to disable access to WPF shared memory. Then, restart Perforator and the WPF application you were profiling.

NoteNote:

Enabling this option may cause a small increase in memory usage and a small decrease in performance when running WPF applications. You should ensure that Perforator disables this option correctly.

Registry Key Setting

The Enable Debug Control checkbox adds or deletes a WPF registry key setting. To add the registry key setting manually, run the following command from a command window:

reg add HKLM\SOFTWARE\Microsoft\Avalon.Graphics /v EnableDebugControl /t REG_DWORD /d 1 /f

To delete the registry key setting manually, run the following command from a command window:

reg delete HKLM\SOFTWARE\Microsoft\Avalon.Graphics /v EnableDebugControl /f

Using Perforator

To use Perforator, start the WPF application whose rendering behavior you want to analyze. Once the application has started, click the Refresh button in Perforator. The application should now appear in the Perforator list box of WPF applications. Select the application and the rendering options you want to analyze. The Perforator data values, such as frame rate, immediately reflect the rendering behavior of the application.


Perforator with application and rendering options selected

Perforator main window with options selected

The following screenshot displays the PhotoDemo sample application with the "Draw software rendering with purple tint" and "Show dirty region support" rendering options enabled:


PhotoDemo sample application displays rendering behavior

Photodemo app showing Perforator rending options

The following sections discuss the major performance issues involved in rendering, and how Perforator options and data output can help you diagnose these issues.

Avoiding Software Rendering

Because the WPF hardware rendering pipeline is substantially faster that its software rendering pipeline, the less application UI that renders in software, the faster rendering in that application will be. Typically the time it takes to render an area in software is proportional to the number of pixels rendered, so be wary of large areas rendered using the software pipeline; small areas are of less concern.

Here are the Perforator options that can help detect software rendering issues:

  • Draw software rendering with purple tint: Draws all areas rendered using the software rendering pipeline with a purple tint. This includes software render targets, software 3D content, and per-primitive software fallback.

  • Num Software Render Targets: Counts the full-window render targets that are running entirely in software. If the count is not 0, this represents a significant performance problem, usually related to machine configuration or the presence of layered windows. Make sure that Microsoft Direct3D is enabled (run dxdiag), ensure that all monitors are set to 32 bits per pixel (BPP) bit depth, and make sure the graphics card is supported by .

  • Num Hardware Render Targets: Counts the full-window render targets that are running in hardware. This number should be equal to the number of windows for the application, times the number of display adapters. This indicates an application is being hardware accelerated wherever possible.

Avoid Large Numbers of Intermediate Render Targets

Intermediate Render Targets are additional images that WPF needs to draw in order to get content ready for drawing to the screen.

  • Maximum SW/HW IRTs per Frame: Shows the maximum number of software or hardware Intermediate Render Targets being applied to render any one frame of the application. Intermediate Render Targets are usually caused by the use of DrawingBrush, VisualBrush, Opacity on a Visual, or Tile modes on a TileBrush. If this number is very high, it can be an indication that the WPF runtime is performing a large amount of work to render your application.

Useful Performance Metrics

  • Dirty Rect Addition rate: Indicates that fast updates are being triggered in your application.

  • Frame rate: Reports the rate at which the application is rendering to the screen. For applications without animation, this value should be near 0, since the dirty region optimizations should avoid drawing except when necessary. Treat this number as an estimate.

  • Estimated video memory usage: Tracks large allocations of video memory made directly by WPF (textures and render targets). This does not track allocations made by a given video driver during rendering, allocations caused by the compilation and loading of pixel or vertex shaders, or allocations for vertex or index buffers. Note that exceeding the available amount of texture memory will usually cause WPF render logic to fall to software, and that multiple displays (multi-mon) has a multiplicative effect on the amount of video memory required for an application.

Dirty-Region Support

Because Windows Presentation Foundation (WPF) only updates portions of the window as required, it can be helpful to visualize what proportion of the window is being updated at any time. The following options help visualize the update behaviors.

  • Show dirty-region update overlay: Causes each update WPF makes to the screen to be indicated by recoloring. This allows you to see what areas are redrawn in a running application, and when.

  • Clear Back Buffer Before Rendering: Causes the window to be cleared before each drawing operation.

  • Disable Dirty Region Support: Causes WPF to redraw the entire window anytime any change is made, instead of only redrawing the portion of the window that has changed. This can be useful for forcing your entire window to update, but be warned: enabling this will cause your application to render much more slowly.

Disabling Rendering Features

Perforator allows you to disable certain performance-intensive operations to determine whether they are causing bottlenecks in your application.

  • Disable Opacity Effects: Disables certain potentially performance-intensive uses of opacity. To avoid this performance issue in general, consider setting opacity on a low-level object, such as Brush, instead of a high-level object, such as Button.

  • Disable per-primitive software fallback: Disables software fallback for individual rendering primitives. Software intermediate render targets and other software rendering cannot be disabled.

  • Disable high-quality image rescaling: WPF rescales large images to look better if they are being displayed at a small size. This operation is performance intensive, especially in applications which have many large images being displayed at reduced sizes on screen. This option allows you to disable this rescaling to see if it is the source of a performance problem. To avoid this, consider decoding your images to a size near the size at which they will be displayed.

  • Disable 3D rendering: Turns off all 3D drawing operations.

ETW Trace Viewer

Event Tracing for Windows (ETW) provides a mechanism for tracing and logging events that are raised by user-mode applications. ETW is implemented in the Windows operating system and provides developers a fast, reliable, and versatile set of event tracing features. The Event Trace tool allows you record, display, and browse ETW log files in a user-interface format that is specific to WPF features.


ETW Trace View main window

Trace View main window

Using ETW Trace Viewer

You can view an ETW log file that you created and saved using the WPF Event Trace profiling tool. Event log files use the default file extension, "etl". Select File from the main menu of ETW Trace Viewer. Than, click the Open to load the desired log file.


ETW Trace Viewer main window with log file

Trace View main window with event log

Once the log file is loaded, ETW Trace Viewer displays a timeline that represents the duration of the event log capture. You can change the unit of measurement for the timeline to be either in seconds or milliseconds. You can choose which types of events you want to view by enabling or disabling specific event types. If you are interested in viewing a small number of event types, you can click the Disable All button to disable all events, and then click the checkboxes for the event you want to enable. The enabled event types for the timeline appear in the bottom right of the ETW Trace Viewer.

You can click and drag the mouse on the time line to view only those events that occurred during the selected area of the timeline. To zoom in on the selected area of the timeline, right click to display the popup menu illustrated in the following screenshot.


ETW Trace Viewer main window with popup menu

Trace View main window with event log

The popup menu allows you to zoom in and out of the timeline, as well as show all events and clear the currently selected area of the timeline. When you zoom in on the timeline, the time interval that is displayed in blue indicates the length of the zoomed in timeline. The time interval that is displayed below, in black, indicates the time relative to the overall duration of the event log capture.


ETW Trace Viewer main window with zoomed in data

Trace View main window with event log

You can click the small boxes on the timeline to display information about a specific event.

Generating an Event Log File

You can also create an ETW log file using ETW Trace Viewer by clicking the Start capture button to begin event logging, and clicking the Stop capture button to end event logging. The event logger generated by using this method does not allow you to customize settings for filtering events. Use the Event Trace tool for creating a custom event logger.

Visual Profiler

Visual Profiler is a performance profiling tool for profiling the use of WPF services, such as layout and event handling, by elements in the visual tree. By analyzing the profiling output of this tool, you can determine which visual elements in your application may be causing performance bottlenecks The Visual Profiler main window displays a set of options that allow you specify how you want to profile your application:

  • Update interval. The granularity of the time to use during profiling.

  • Display overlay. The display overlay option allows you to display CPU resource usage—darker red overlays indicate greater CPU resources.


Visual Profiler main window

Visual Profiler main window

The Value of Visual Profiling

The WPF Visual Profiler presents performance issues in the context of the basic building blocks that are used to construct visual scenes in your application. These building blocks include high-level objects, such as Button and TextBlock controls, as well as low-level objects, such as Line and Ellipse elements. Instead of describing performance issues in terms of call graphs of functions names, Visual Profiler describes these issues using the representation of visual objects. This is similar to the way the Windows SDK tool, UI Spy, represents information. For more information, see UI Spy (UISpy.exe).

In order to analyze the breadth of WPF performance issues, it is necessary to understand the role and scope of underlying WPF services. These services include layout, rendering, and animation. Visual Profiler provides a graphical representation of how WPF services are allocated among application objects. For example, when Visual Profiler displays the visual tree of application objects, it overlays different shades of red on the objects in order to represent the relative amount of resources the object is using. An object that is displayed with a darker red overlay represents an object that uses a higher proportion of resources that an object with a lighter red overlay. More importantly, Visual Profiler provides a breakdown of the amount of specific WPF resources an object consumes.

Using Visual Profiler

To use Visual Profiler, start the WPF application you want to profile. Once the application starts, click the Start Profiling button in Visual Profiler. The following dialog box appears:


Profiling Configuration dialog box

Visual Profiler process list

The Profiling Configuration dialog box lists all the currently running WPF applications. You can list applications that start after this dialog box is open by clicking the Refresh button. Select the application you want to profile. Next, select the Events tab to choose the application and element events you want to profile.


Events Configuration dialog box

Visual Profiler configuration settings

You can set the Visual Profiler configuration to enable or disable the profiling of the following application events:

Application events Description

Animation Render Handler

When animations are enabled, this handler processes and updates the animation, which causes properties to change and, in turn, rendering to occur.

Layout

Occurs during the measure, arrange, and render pass.

Mark Visible Realizations

Occurs when creating realizations for text and bitmap effects.

Media Render

Occurs when rendering video.

Render

Occurs during the render pass.

Text Formatting

Occurs when formatting text.

Time Manager Tick

Occurs when the animation is ticking. This event can trigger the animation render handler.

Update Effective Value

Occurs when the property engine changes the value of a DependencyProperty.

Update Realizations

Occurs when text glyphs are updated.

Visual Hit Test

Occurs during the hit test pass, which determines which visual object has been hit.

You can set the Visual Profiler configuration to enable or disable the profiling of the following element events:

Element events Description

Layout

Occurs during the measure, arrange, and render pass.

Mark Visible Realizations

Occurs when creating realizations for text and bitmap effects.

Render

Occurs during the render pass.

Visual Hit Test

Occurs during the hit test pass, which determines which visual object has been hit.

When you have finished selecting the application and profiling options, click the OK button to begin profiling the application.

Run your application and the Visual Profiler tool side by side and notice the changing values in the tool. By expanding the visual tree hierarchy, you can select a specific visual object to profile, such as a Grid control. The CPU Usage section of the Visual Profiler gives you a precise breakdown of the use of WPF services by both the object and application. The CPU Utilization data for the element lists:

  • Inclusive Time The CPU utilization for the element and all its descendants.

  • Exclusive Time The CPU utilization for only the element.


Visual Profiler display output

Visual Profiler display output

NoteNote:

The visual tree view lists the type of element, followed by a numeric value. The numeric value for the last element can give you an indication of the total number of elements in the visual tree hierarchy of your application. In this case, the last element, the AdornerLayer, is followed by the value, "210". However, as new elements are created or deleted during changes to the application state, there may be more, or less, than 210 elements in the visual tree, so the numeric value of the last element is most useful during the initial creation of the visual tree view.

Visual Profiler overlays different shades of red on the objects in the visual tree in order to represent the relative amount of resources the object is using. An object that is displayed with a darker red overlay represents an object that uses a higher proportion of resources that an object with a lighter red overlay.


Visual Profiler display output with overlays

Visual Profiler showing display overlays

Working Set Analyzer

The Working Set Analyzer is a WPF performance analysis tool that provides information on the memory usage of a specified process. This tool allows you to generate a snapshot of application memory usage information at a particular application state.

Working Set of an Application

The working set of an application is a collection of those pages in its virtual address space that have been recently referenced. It includes both shared and private data. The shared data includes pages that contain all instructions your application executes, including those in your DLLs and the system DLLs. As the working set size increases, memory demand increases. For more information on the working set, see Process Working Set.

Virtual Address Dump (VaDump) Utility

Virtual Address Dump (VaDump) creates a listing that contains information about the memory usage of a specified process. This tool is available as part of the Windows SDK, and is located in the Tools directory:

~\Program Files\Microsoft Visual Studio 8\Common7\Tools\Bin\winnt

NoteImportant:

You must ensure that the system execution path includes the directory location of VaDump. Otherwise, Working Set Analyzer will not function correctly.

Using Working Set Analyzer

To use Working Set Analyzer, start the WPF application you want to profile. When you run Working Set Analyzer, the bottom part of the main window lists all the currently running processes:


Working Set Analyzer main window

Working Set Viewer main window

Select the process whose working set you want to analyze; then, click the Capture button. The Working Set Analyzer first invokes VaDump to generate memory usage information. Next, it parses the information and presents it in a graphically-rich format.

NoteNote:

The working set data represents a static view of memory usage. You may want to generate several sets of working set data at different points in your application, and compare the differences in memory usage.

Once the working set data is ready to view, Working Set Analyzer generates a tree view that represents the dynamic data, system data, and application modules.


Working Set Analyzer memory usage categories

Working Set Viewer usage categories

For WPF applications, the Avalon Modules category contains modules that are system-specific to WPF. Click the category you want to display and a set of pie charts displays. For example, clicking the Avalon Modules category displays the following information on the left side of the window.


Working Set Analyzer memory usage pie chart

Working Set Viewer memory usage pie chart

The caption at the top displays the total size of the working set category. In this case, Avalon Modules represents 8700KB of memory usage. This large pie chart represents the individual memory usage of all modules that define the Avalon Modules category.

NoteNote:

The size of a memory usage category reflects the memory usage of your application at the moment the working set information was captured.

The small pie chart represents the memory usage of shared, sharable, and private bytes.


Working Set Analyzer memory usage pie chart

Working Set Viewer memory usage pie chart

The shared bytes category represents the amount of memory that could be potentially shared by other WPF applications.

Viewing Application Memory Usage

To view the memory usage for your application, select the name of the executable file from the Other Modules category in the Working Set tree view.


Working Set Analyzer memory usage categories

Working Set Viewer usage categories

Saving and Reloading Working Set Analyzer Files

To save the current working set usage information, select File from the main menu of Working Set Analyzer. Then, click the Save VADump output button. Once you have saved the working set usage information, you can generate another snapshot of memory usage by clicking the Capture button. To reload a file containing VADump content, select File from the main menu of Working Set Analyzer. Then, click the Open VADump output button.

Using a Timer Delay to Capture Working Set Information

The Working Set Analyzer provides a time delay feature that allows you to capture working set usage information after a specified interval of time. Select File from the main menu of Working Set Analyzer. Then, click the Launch process button.


Launch process dialog box

Launch process dialog box

Specify the application you want to run, using the Browse button if needed. Next, enter any arguments for the application. Finally, enter the number of seconds you want to delay the capture of memory usage information. Then, click the Launch button. The status text at the bottom of the Working Set Analyzer counts down the number of remaining seconds until capture, which allows you time to modify your application's state. Once the capture is complete, the status text displays "Done".

Other Performance Tool Resources

Windows Presentation Foundation (WPF) also provides debug tracing support.

Debug Tracing Support for WPF

The PresentationTraceSources class provides debug tracing support for Windows Presentation Foundation (WPF) applications. Tracing is a diagnostics system by which an application's progression can be tracked. The tracing statements report information, much the way the WriteLine method is often used. However, tracing statements can be switched on or off by using a configuration file. In addition, the output of tracing statements can be customized.

For other related .NET Framework 3.0 diagnostic classes, see System.Diagnostics.

See Also

Other Resources

Optimizing Windows Presentation Foundation Application Performance
Graphics Rendering Tiers
Windows Presentation Foundation Graphics Rendering Overview
UI Spy (UISpy.exe)