Sub topic 8
Finding expensive code with the CPU Profiler
This chapter assumes you can launch DevTools and connect it to a running app. It also assumes you know why profile mode exists and have seen the Performance view flag slow frames. The CPU Profiler answers the next question: when a frame or a user action is slow, which Dart code was running during that time?
What the CPU Profiler measures
The CPU Profiler is a sampling profiler. While you record, the Dart VM periodically captures the call stack of the isolate and stores each capture as a sample. DevTools then groups the samples by function. A function that appears in 400 of 500 samples was on the stack for about 80% of the recording.
Sampling has three consequences:
- It does not time individual calls. It tells you where time accumulated, not how long one call took.
- Very short functions can be missed, and results vary a little between recordings. Treat small differences as noise.
- Overhead is low, so the profile reflects normal behavior. This holds only in profile mode, as explained below.
The profiler works on one isolate at a time. A Flutter app starts with the main isolate, where your build methods and event handlers run. If you move work to another isolate, select that isolate in DevTools to see its samples.
Prepare the app
Profile in profile mode on a real device whenever you can. Debug mode compiles Dart just-in-time with assertions and extra checks, so the profile shows costs your users never pay. The hottest function in a debug profile may not matter in release.
# Run the app in profile mode on a connected device
flutter run --profile
# Start DevTools on its own, then connect using the VM service URI printed by flutter run
dart devtoolsOpen the CPU Profiler tab. If you opened DevTools from your IDE, the tab sits beside Performance and Memory.
A slow example to profile
The following app counts primes below a limit using a deliberately naive algorithm. The work runs inside a button handler on the main isolate, so the UI freezes while it runs. It is a stand-in for real problems such as parsing a large JSON file, resizing an image, or filtering a big list.
import 'package:flutter/material.dart';
bool isPrime(int n) {
if (n < 2) return false;
for (var i = 2; i < n; i++) {
if (n % i == 0) return false;
}
return true;
}
int countPrimes(int limit) {
var count = 0;
for (var n = 0; n < limit; n++) {
if (isPrime(n)) count++;
}
return count;
}
void main() => runApp(const MaterialApp(home: PrimeScreen()));
class PrimeScreen extends StatefulWidget {
const PrimeScreen({super.key});
@override
State<PrimeScreen> createState() => _PrimeScreenState();
}
class _PrimeScreenState extends State<PrimeScreen> {
int? _result;
void _run() {
// Runs on the main isolate and blocks the UI until it finishes.
setState(() => _result = countPrimes(200000));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Primes')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const CircularProgressIndicator(),
const SizedBox(height: 24),
Text(_result == null ? 'Not run yet' : 'Primes: $_result'),
const SizedBox(height: 24),
ElevatedButton(onPressed: _run, child: const Text('Count')),
],
),
),
);
}
}The spinner is there on purpose. When you tap the button, the spinner stops moving, which is a visible sign that the main isolate is blocked.
Record a profile
- Run the app in profile mode and open the CPU Profiler.
- Select the main isolate if more than one is listed.
- Press the record button.
- Tap Count in the app and wait for the result to appear.
- Press stop.
Record only the interaction you care about. A long recording full of idle time makes the hot spot a smaller share of the samples and harder to see. The Clear button discards the current data so you can start a fresh recording.
If a problem happens during startup, you can't press record in time. Use the option to load the profile recorded since the app started, if your DevTools version offers it. Otherwise, add a way to repeat the slow action, such as a button or a hot restart.
Read the results
DevTools presents the same samples in several views. The choice of view changes what question you can answer.
| View | Orientation | Best for |
|---|---|---|
| Bottom Up | Starts from the functions where the CPU spent its own time and expands to their callers | Finding the single most expensive function |
| Call Tree | Starts from entry points such as `main` and expands to callees | Understanding the path that led to the cost |
| Method Table | Lists every method with its totals and callers/callees | Looking up one specific method |
| Flame Chart | Shows stacks over time, with call depth vertically and width as duration | Seeing the shape and order of the work |
Self time and total time
Two columns appear in most views, and confusing them leads to wrong conclusions.
- Self time is time spent in the function's own code, excluding functions it calls.
- Total time is time spent in the function and everything it called.
In the example, countPrimes has a high total time because it calls isPrime 200,000 times, but its self time is small. isPrime has the high self time because the modulo loop runs inside it. Sort by self time to find where the CPU does the work. Sort by total time to find which of your own entry points owns the cost.
In the Bottom Up view you should see isPrime at or near the top, with countPrimes and _PrimeScreenState._run below it as callers. That caller chain tells you the work came from the button handler.
The Flame Chart
In the Flame Chart, the x-axis is time and each row down is a deeper call. A wide bar is a function that stayed on the stack for a long time. Hover over a bar for its name and duration, and click it to see the source location in the details panel. A single wide isPrime row under countPrimes confirms one long, uninterrupted block. Many narrow bars instead point to death by a thousand cuts, such as a build method that runs too often.
Reduce the noise
A raw profile includes frames from the engine and the Dart core libraries. Use the filter options to hide native code and core Dart libraries when you want to focus on your own packages. Do not leave them hidden when investigating a suspected framework cost, for example a very deep widget tree. Filtering hides the evidence you need in that case.
You can also search the call tree by name, which helps in a large profile when you already suspect a class.
Connect the profile to frames
Use the Performance view first and the CPU Profiler second. The Performance view tells you which frames missed their deadline and whether the UI or raster thread was slow. If the UI thread is the slow one, the cause is Dart code, and the CPU Profiler is the right tool. If the raster thread is slow, the cost is in drawing, such as expensive shaders, saveLayer calls or large images, and the CPU Profiler on Dart code will show little.
A profile that shows build methods near the top is a different problem from one that shows your own algorithm. If build dominates, look at what you compute inside it or how often it is called. If your function dominates, move or optimize that function.
Label your own code
Sampling gives you function names, so a long anonymous closure can be hard to identify. Extract the work into a named function, or add a timeline event so it appears as a labeled block in the Performance view.
import 'dart:developer';
int sumOfSquares(List<int> values) {
return Timeline.timeSync('sumOfSquares', () {
var total = 0;
for (final v in values) {
total += v * v;
}
return total;
});
}Use timeline events sparingly. They add overhead, and a profiler that has to look through many tiny events is harder to read.
Fix the hot spot and verify
There are two kinds of fix, and a profile helps you pick between them.
- Make the code cheaper. In the example,
isPrimechecks every number up ton. Stopping at the square root ofnmakes it far faster. - Move the work off the main isolate. If the work is still heavy after optimizing, run it where it can't block frames.
Here is the second fix using compute, which runs a top-level function in a separate isolate. The functions isPrime and countPrimes stay as above, with isPrime optimized.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
bool isPrime(int n) {
if (n < 2) return false;
for (var i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
int countPrimes(int limit) {
var count = 0;
for (var n = 0; n < limit; n++) {
if (isPrime(n)) count++;
}
return count;
}
void main() => runApp(const MaterialApp(home: PrimeScreen()));
class PrimeScreen extends StatefulWidget {
const PrimeScreen({super.key});
@override
State<PrimeScreen> createState() => _PrimeScreenState();
}
class _PrimeScreenState extends State<PrimeScreen> {
int? _result;
Future<void> _run() async {
final count = await compute(countPrimes, 200000);
if (!mounted) return;
setState(() => _result = count);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Primes')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const CircularProgressIndicator(),
const SizedBox(height: 24),
Text(_result == null ? 'Not run yet' : 'Primes: $_result'),
const SizedBox(height: 24),
ElevatedButton(onPressed: _run, child: const Text('Count')),
],
),
),
);
}
}Record the same interaction again. Three things should now be true: the spinner keeps moving, the Performance view shows no long frames during the tap, and the main isolate's profile no longer lists isPrime as a hot spot. The work now shows up under the other isolate, so you can select it and confirm it is lighter than before.
Common mistakes
- Profiling in debug mode and optimizing code that is fast in release.
- Reading total time as if it were self time, and blaming an entry point instead of the function doing the work.
- Recording too long, so the slow action is a tiny fraction of the samples.
- Hiding native and core library frames, then missing a cost in the framework.
- Looking only at the main isolate when the slow work runs in another one.
- Chasing the Dart code when the Performance view shows the raster thread is the slow one.
Exercise
A profile of a slow list screen shows _ItemListState.build with 90% total time and 1% self time. jsonDecode has 70% total time and 65% self time and appears under build in the Call Tree. Which function should you fix first, and which two options do you have?
Show answer
Fix the jsonDecode call, because it has the high self time, so the CPU spends its time there and not in build itself. The 90% total time on build only shows that build calls the expensive code. You can stop decoding inside build, for example by decoding once and caching the result, or move the decoding off the main isolate with compute. Then record the same action again in profile mode to verify that jsonDecode no longer dominates the main isolate.
Exercise
You record a profile in the Performance view and find that the UI thread is fast but the raster thread misses its deadline. The CPU Profiler shows almost nothing unusual. Why, and where do you look next?
Show answer
The CPU Profiler samples Dart code on the isolate, and the slow work is in rendering, which runs on the raster thread. Look at the Performance view's frame analysis for causes such as expensive layers, saveLayer calls, large images or heavy shaders, and reduce that drawing work.