CodeBlanks Logo Icon CodeBlanks

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.

Practice 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').

Starter code

main.dart
// import the dart:developer library

void main() {
  // start a Timeline section, run a loop, close with finishSync
  // print sum and Timeline info
}

Sample solution

main.dart
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');
}

Expected output

Sum: 4950
Timeline: compute

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 The dart:developer import

Question
import 'dart:____' as developer;
Answer
import 'dart:developer' as developer;

Explanation: dart:developer is imported with the developer alias.

2 Match the profiling parts

Term Meaning
Timeline Profile section
startSync Section start
finishSync Section end
dart:developer Library

3 What does Timeline.startSync do?

  • Starts a profile section Correct answer
  • crypto
  • Stopwatch
  • bcrypt

Explanation: Timeline.startSync starts a profile section.

All lessons in Advanced