Dart
Profiling
Learn DevTools profiling.
DevTools and profiling
DevTools is the official profiling and debugging tool for Dart and Flutter. It offers CPU profile, memory timeline, network and widget inspector tabs. It opens with dart devtools and connects to a running app.
To add profile markers from code, use the Timeline class in the dart:developer library. Timeline.startSync('name') starts a section; Timeline.finishSync() closes it. These sections appear as labeled blocks in the DevTools timeline tab; they show how long each piece of code takes. For accurate results, run the app in release mode while profiling.
Marking sections with Timeline
Timeline.startSync('name') starts a profile section. Then the measured code runs. Finally Timeline.finishSync() is called. The section name appears in the DevTools timeline; so you see which operation takes which amount of time.
Example: Timeline.startSync('compute'); var sum = 0; for (var i = 0; i < 100; i++) { sum += i; } Timeline.finishSync();. Here the loop appears as a 'compute' labeled block in the timeline. sum (0+1+...+99 = 4950) is deterministic; it can be printed to confirm the section closed correctly. Every startSync must have a matching finishSync.
Exercise Profile with Timeline
Add import 'dart:developer' as developer;. In main call developer.Timeline.startSync('compute'). Write a for loop with var sum = 0;: i from 0 to 99 (exclusive 100), sum += i. Then call developer.Timeline.finishSync(). Print with print('Sum: $sum') and print('Timeline: compute').
Show example solution
import 'dart:developer' as developer;
void main() {
developer.Timeline.startSync('compute');
var sum = 0;
for (var i = 0; i < 100; i++) {
sum += i;
}
developer.Timeline.finishSync();
print('Sum: $sum');
print('Timeline: compute');
}
Test yourself
-
The dart:developer import
import 'dart:____' as developer;
Show answer
import 'dart:developer' as developer;
-
Match the profiling parts
- Timeline
- Profile section
- startSync
- Section start
- finishSync
- Section end
- dart:developer
- Library
-
What does Timeline.startSync do?
- Starts a profile section
- crypto
- Stopwatch
- bcrypt
Show answer
Starts a profile section — Timeline.startSync starts a profile section.
Next lesson: Summary - Performance