Sub topic 11
Adding your own timeline events
The Timeline Events tab shows what the framework did during a frame, such as build, layout, and paint. It cannot know which of your functions matter to you. A frame might show 14 ms in build, with nothing to say which part of your code used it. Custom timeline events fix this. You wrap your own work in a named span, and that span appears by name in the trace.
This chapter assumes you can run an app in profile mode, select a frame in the frames chart, and open the Timeline Events tab. It also assumes you know the UI thread versus raster thread split from earlier chapters.
What a custom timeline event is
The dart:developer library has a Timeline class. When you call it, the Dart VM writes a begin marker, runs your code, and writes an end marker. DevTools reads these markers from the same trace that holds the framework's own events. It draws your span in the flame chart, nested inside whatever was running when you started it.
There are three kinds of event:
| Kind | API | Use it for |
|---|---|---|
| Synchronous span | `Timeline.timeSync`, or `Timeline.startSync` and `Timeline.finishSync` | Work that runs start to finish without `await` |
| Instant marker | `Timeline.instantSync` | A single point in time, such as "cache miss" |
| Asynchronous span | `TimelineTask` | Work that crosses `await` points and may span several frames |
Most of the time you want the first kind.
Wrapping a block with timeSync
Timeline.timeSync takes a name and a function. It records a span around the function and returns the function's result. That return value makes it easy to add to existing code, because you wrap the body and nothing else changes.
import 'dart:developer';
List<String> parseCatalog(String raw) {
return Timeline.timeSync('parse_catalog', () {
return raw.split('\n').where((line) => line.isNotEmpty).toList();
});
}Each call to parseCatalog now produces a parse_catalog span. If you call it from build, the span sits inside the build events of the frame. If you call it from a button handler, it sits on its own, outside any build.
Choose names you can search for. A name like parse_catalog tells you what happened. A name like work does not.
Attaching arguments
timeSync accepts an arguments map. DevTools shows the map in the details panel when you select the event. This is useful when the same code runs with different inputs and you want to know which input was slow.
import 'dart:developer';
List<String> parseCatalog(String raw) {
return Timeline.timeSync(
'parse_catalog',
() => raw.split('\n').where((line) => line.isNotEmpty).toList(),
arguments: {'bytes': raw.length},
);
}Keep arguments small and cheap to compute. They are evaluated every time the code runs, even when nobody is recording a trace. raw.length is fine. Building a long string of the whole input is not.
Manual start and finish
Sometimes you cannot wrap the work in one closure. An example is a method with several early returns. For those cases, use startSync and finishSync. Every startSync needs exactly one finishSync, so put the finish in a finally block.
import 'dart:developer';
int countValidRows(List<String> rows) {
Timeline.startSync('count_valid_rows', arguments: {'rows': rows.length});
try {
if (rows.isEmpty) return 0;
var count = 0;
for (final row in rows) {
if (row.trim().isNotEmpty) count++;
}
return count;
} finally {
Timeline.finishSync();
}
}Without the finally, an exception between the two calls leaves the span open. Later spans on that thread would then nest under it, and the trace would look wrong.
Nesting events
Synchronous spans nest by time. If one timeSync call runs inside another, the inner span appears below the outer one in the flame chart. Nesting lets you break a slow step into parts.
import 'dart:developer';
class Product {
Product(this.name);
final String name;
}
List<Product> loadProducts(String raw) {
return Timeline.timeSync('load_products', () {
final lines = Timeline.timeSync(
'split_lines',
() => raw.split('\n'),
);
return Timeline.timeSync(
'build_products',
() => lines.where((l) => l.isNotEmpty).map(Product.new).toList(),
);
});
}In the Timeline Events tab, load_products is a bar and split_lines and build_products are narrower bars directly beneath it. The widths show how much of the parent's time each child used. If split_lines is nearly as wide as load_products, the splitting is your cost.
Finding your events in DevTools
Follow these steps to see your events:
- Run the app with
flutter run --profile -d <device-id>. - Open the Performance view and trigger the code path that contains your event.
- Select a slow frame in the frames chart.
- Open the Timeline Events tab and look in the UI thread row for your event name.
- Click the event to see its duration and any arguments.
If the event does not appear, check these causes first:
- The code did not run during the frame you selected. An event fired from a tap handler belongs to the frame after the tap, and not necessarily the one you clicked.
- The work ran in another isolate. Events from an isolate started with
Isolate.runappear on that isolate's thread, not the UI thread. This is expected, and it is also the reason that moving work to an isolate removes it from your frame time. - The trace was cleared or has scrolled out of the recorded window. Reproduce the slow action and look again.
Instant markers
Some things have no duration, such as "the cache was empty" or "retry number 3 started". Use Timeline.instantSync for these. It records a single point on the timeline.
import 'dart:developer';
final Map<String, String> _cache = {};
String lookup(String key) {
final hit = _cache[key];
if (hit == null) {
Timeline.instantSync('cache_miss', arguments: {'key': key});
return _cache[key] = key.toUpperCase();
}
return hit;
}Instant markers work well for annotating a slow frame. If a frame is slow and a cache_miss marker appears inside it, you have a lead.
Asynchronous work with TimelineTask
A synchronous span must start and end on the same thread without yielding, so it cannot cover an await. For work that spans several event-loop turns, such as a network call followed by parsing, use TimelineTask. Each task has its own id, so overlapping tasks do not get mixed up.
import 'dart:developer';
Future<String> fetchAndParse(Future<String> Function() fetch) async {
final task = TimelineTask();
task.start('fetch_and_parse');
try {
final raw = await fetch();
task.instant('fetched', arguments: {'bytes': raw.length});
return raw.trim();
} finally {
task.finish();
}
}Async tasks are drawn as their own tracks and are not nested under the frame. They tell you how long an operation took from start to finish. They do not show you what the UI thread did. If the question is "why was this frame slow", prefer synchronous events on the UI thread. Use async tasks for latency of operations that happen between frames.
A complete example
This app does a slow step inside build and marks it with an event. Run it in profile mode and the span is easy to spot.
import 'dart:developer';
import 'package:flutter/material.dart';
int slowSum() {
var total = 0;
for (var i = 0; i < 50000000; i++) {
total += i % 7;
}
return total;
}
class TracedText extends StatelessWidget {
const TracedText({super.key});
@override
Widget build(BuildContext context) {
final result = Timeline.timeSync('slow_sum', slowSum);
return Text('Result: $result');
}
}
void main() {
runApp(const MaterialApp(home: Scaffold(body: Center(child: TracedText()))));
}Select the frame that built TracedText. The slow_sum span fills almost the whole build event. You have confirmed the cause with a name that came from your own code. The fix is the Isolate.run approach from the common fixes chapter. After applying it, record again. The slow_sum span should disappear from the UI thread, and the frame should fit the budget.
Costs and good habits
- Spans are cheap but not free. A single span costs little. A span inside a loop that runs a million times fills the trace buffer and slows the code you are measuring. Put the span around the loop, not inside it.
- Name stable things. Use a fixed name and put varying data in
arguments. If the name contains an id, every call looks like a different event. - Remove or keep deliberately. Spans around important operations are fine to leave in. Spans added for a one-off investigation should be removed so the trace stays readable.
- Combine with enhanced tracing. The enhance-tracing options give you per-widget build, layout, and paint events. Your events then show which of your functions was running inside those widgets.
Exercise
A method render() has three early return statements, and you want one timeline span around its whole body. Which API do you use, and what must you add to keep the trace correct if the method throws?
Show answer
Use Timeline.startSync('render') at the top and Timeline.finishSync() in a finally block that wraps the body. The finally runs on every return and on exceptions, so the span is always closed. Alternatively, move the body into a closure and wrap it in Timeline.timeSync.
Exercise
You add Timeline.timeSync('heavy', ...) around a call that runs through Isolate.run, but you cannot find heavy in the UI thread row of the selected frame. Where is it, and what does this tell you about the frame?
Show answer
The span was recorded on the other isolate's thread, so it is not in the UI thread row. The UI thread is not doing that work, so it does not count against the frame's UI time. If the frame is still slow, the cause is elsewhere.