Profiling

suggest change

A benchmark tells you how long something takes. A profiler tells you where the time and memory go. Profile before you optimize: the slow part is often not where you expect it.

The Dart VM has profiling built in. Every non-AOT Dart program can expose the VM service, a JSON-RPC protocol over WebSocket. The tools you use are all clients of it:

This article covers each one. For measuring and comparing timings see Benchmarks, and for common optimizations see Performance.

All examples were run with Dart 3.13 and vm_service 15.4.

A program to profile

The examples profile this program, saved as bin/workload.dart. It parses JSON orders and adds up totals per customer:

import 'dart:convert';

class Order {
  final int id;
  final String customer;
  final double amount;
  Order(this.id, this.customer, this.amount);
}

List<Order> parseOrders(String json) {
  final list = jsonDecode(json) as List;
  return [
    for (final m in list.cast<Map<String, dynamic>>())
      Order(m['id'] as int, m['customer'] as String,
          (m['amount'] as num).toDouble()),
  ];
}

String slugify(String s) {
  var out = '';
  for (final ch in s.toLowerCase().split('')) {
    out += RegExp(r'[a-z0-9]').hasMatch(ch) ? ch : '-';
  }
  return out;
}

Map<String, double> totalsByCustomer(List<Order> orders) {
  final totals = <String, double>{};
  for (final o in orders) {
    final key = slugify(o.customer);
    totals[key] = (totals[key] ?? 0) + o.amount;
  }
  return totals;
}

String makeInput(int n) => jsonEncode([
      for (var i = 0; i < n; i++)
        {'id': i, 'customer': 'Customer Number ${i % 500}', 'amount': i * 0.25},
    ]);

void main() {
  final sw = Stopwatch()..start();
  final input = makeInput(200000);
  final orders = parseOrders(input);
  final totals = totalsByCustomer(orders);
  print('${orders.length} orders, ${totals.length} customers '
      'in ${sw.elapsedMilliseconds} ms');
}
$ dart run bin/workload.dart
200000 orders, 500 customers in 1885 ms

Is the time spent in JSON decoding, in creating objects, or in the map? Let's find out.

Starting a program with the VM service

Add --observe to dart run:

$ dart run --observe bin/server.dart
The Dart VM service is listening on http://127.0.0.1:8181/RdqX6Y2IIro=/
The Dart DevTools debugger and profiler is available at: http://127.0.0.1:8181/RdqX6Y2IIro=/devtools/?uri=ws://127.0.0.1:8181/RdqX6Y2IIro=/ws

Open the second URL in a browser. The random part of the URL is an authentication code, which protects the service from other web pages. --observe is a shortcut for several options (dart help -v run lists them):

Other useful options:

Option What it does
--pause-isolates-on-start stop before main, so you can start recording first
--write-service-info=<file-uri> write the service URI as JSON to a file, for scripts
--disable-service-auth-codes no auth code in the URI (only on a trusted machine)
--no-serve-devtools service only, no DevTools web app
--no-dds connect directly to the VM, without the Dart Development Service proxy

To open DevTools for a program that is already running, or for one started by another tool, run dart devtools and paste the service URI into the page, or pass the URI on the command line: dart devtools http://127.0.0.1:8181/RdqX6Y2IIro=/.

Observatory was the older web UI of the VM service. It has been replaced by DevTools: the service root URL now redirects to DevTools. Old guides that mention --observe and Observatory pages describe DevTools pages today.

Raw VM flags

dart run only accepts the options listed in its help. Low-level VM flags have to be passed to dart itself, before the script name:

$ dart run --profile-period=250 bin/workload.dart
Could not find an option named "--profile-period".

$ dart --observe --profile-period=250 bin/workload.dart

dart --help --verbose lists all VM flags. The ones related to profiling:

Flag Default Meaning
--profiler off enable the CPU sampler (implied by --observe)
--profile-period=<us> 1000 time between CPU samples in microseconds, minimum 50
--max-profile-depth=<n> 128 maximum stack frames recorded per sample
--sample-buffer-duration=<s> about 4 s size the sample ring buffer to hold N seconds
--profile-startup off keep the first samples instead of overwriting old ones
--profile-vm off also record native (C++) frames of the VM
--timeline-recorder=<r> ring where timeline events go: ring, endless, file, perfettofile, systrace and others
--timeline-streams=<list> none which streams to record: Dart, GC, Compiler, Isolate, Microtask, VM, all and others

The sampler keeps samples in a ring buffer. For a long-running program the oldest samples are overwritten, so a profile covers only the last few seconds unless you raise --sample-buffer-duration, at the cost of memory.

The DevTools CPU Profiler

On the CPU Profiler page click Record, let the program do the slow work, then Stop. For a short program started with --pause-isolates-on-exit, click Load all CPU samples instead after it finishes.

The page shows the same data in several views:

A profiler doesn't time every call. It interrupts the thread periodically (every --profile-period microseconds) and records the stack. A function that appears in 30% of the samples used about 30% of the time. That makes profiling cheap, but short programs give few samples, so the numbers are approximate. The DevTools "CPU sampling rate" drop-down changes the period at run time. On Windows, the effective sampling rate is lower than the period suggests.

Toggle Hide core Dart libraries off when you need to see what inside dart:core is slow (like the RegExp internals below), and on when you want to see only your own code.

Profiling from code with package:vm_service

Everything DevTools shows comes from the VM service, and you can get the same data in a script. That is handy in CI, on a remote machine, or when you want a quick text report. Add the package as a dev dependency:

$ dart pub add dev:vm_service

This script runs another Dart program under the VM service, waits until it finishes, downloads the CPU samples and prints the top functions. Save it as bin/profile.dart:

import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:vm_service/vm_service.dart';
import 'package:vm_service/vm_service_io.dart';

/// Usage: dart run bin/profile.dart <script.dart>
Future<void> main(List<String> args) async {
  final infoFile = File('${Directory.systemTemp.path}/vm-info-$pid.json');
  final target = await Process.start(Platform.resolvedExecutable, [
    'run',
    '--observe=0', // VM service on a free port, profiler on
    '--no-serve-devtools',
    '--pause-isolates-on-start',
    '--write-service-info=${infoFile.uri}',
    args.first,
  ]);
  target.stdout.transform(utf8.decoder).listen(stdout.write);
  target.stderr.drain<void>();

  // Wait until the VM writes its connection info.
  while (!infoFile.existsSync() || infoFile.lengthSync() == 0) {
    await Future<void>.delayed(const Duration(milliseconds: 50));
  }
  final info = jsonDecode(infoFile.readAsStringSync()) as Map;
  final httpUri = Uri.parse(info['uri'] as String);
  final wsUri = httpUri.replace(scheme: 'ws', path: '${httpUri.path}ws');
  final service = await vmServiceConnectUri(wsUri.toString());

  final vm = await service.getVM();
  final isolateId = vm.isolates!.first.id!;

  var started = false;
  Future<void> start() async {
    if (started) return;
    started = true;
    await service.resume(isolateId);
  }

  final exited = Completer<void>();
  service.onDebugEvent.listen((e) {
    if (e.kind == EventKind.kPauseStart) start();
    if (e.kind == EventKind.kPauseExit) exited.complete();
  });
  await service.streamListen(EventStreams.kDebug);
  final isolate = await service.getIsolate(isolateId);
  if (isolate.pauseEvent?.kind == EventKind.kPauseStart) await start();
  await exited.future;

  // Program finished: fetch every CPU sample the VM still has.
  final cpu = await service.getCpuSamples(isolateId, 0, 1 << 62);
  report(cpu);

  await service.resume(isolateId);
  await service.dispose();
  await target.exitCode;
  infoFile.deleteSync();
}

void report(CpuSamples cpu, {int top = 6}) {
  final self = <int, int>{};
  final inclusive = <int, int>{};
  final byTag = <String, int>{};
  for (final s in cpu.samples!) {
    final stack = s.stack!; // indexes into cpu.functions, leaf first
    if (stack.isEmpty) continue;
    self.update(stack.first, (n) => n + 1, ifAbsent: () => 1);
    for (final f in stack.toSet()) {
      inclusive.update(f, (n) => n + 1, ifAbsent: () => 1);
    }
    byTag.update(s.userTag ?? '?', (n) => n + 1, ifAbsent: () => 1);
  }
  final total = cpu.sampleCount!;
  String pct(int n) => (100 * n / total).toStringAsFixed(1).padLeft(5);

  String name(int i) {
    final f = cpu.functions![i].function;
    if (f is NativeFunction) return '[native] ${f.name}';
    final fn = f as FuncRef;
    final owner = fn.owner;
    if (owner is! ClassRef) return fn.name!;
    final cls = owner.name!.split('&').last; // drop mixin application noise
    return '$cls.${fn.name}';
  }

  void table(String title, Map<int, int> counts) {
    print('\n$title');
    final ids = counts.keys.toList()
      ..sort((a, b) => counts[b]!.compareTo(counts[a]!));
    for (final i in ids.take(top)) {
      print('  ${pct(counts[i]!)}%  ${name(i)}');
    }
  }

  print('\n$total samples, period ${cpu.samplePeriod} us');
  table('Self time (function at the top of the stack):', self);
  table('Total time (function anywhere on the stack):', inclusive);
  print('\nBy user tag:');
  byTag.forEach((tag, n) => print('  ${pct(n)}%  $tag'));
}

How it works:

The Isolate class of package:vm_service has the same name as the one in dart:isolate. If you need both in one file, use import 'package:vm_service/vm_service.dart' hide Isolate;.

Running it on the workload:

$ dart run bin/profile.dart bin/workload.dart
The Dart VM service is listening on http://127.0.0.1:56041/mcTSreJmFe8=/
200000 orders, 500 customers in 965 ms

67 samples, period 1000 us

Self time (function at the top of the stack):
   26.9%  _RegExp._ExecuteMatch
   19.4%  _RegExp._RegExp
   17.9%  _StringBase.+
   16.4%  [native] ZwWaitForAlertByThreadId
    3.0%  _GrowableList._allocateData
    1.5%  makeInput

Total time (function anywhere on the stack):
   83.6%  main
   83.6%  <anonymous closure>
   83.6%  _RawReceivePort._handleMessage
   64.2%  slugify
   64.2%  totalsByCustomer
   26.9%  _RegExp._ExecuteMatch

By user tag:
  100.0%  Default

How to read this:

The fix is to process the whole string with one precompiled pattern instead of one RegExp and one new string per character:

final _notSlugChar = RegExp(r'[^a-z0-9]');

String slugify(String s) => s.toLowerCase().replaceAll(_notSlugChar, '-');

Profiling again:

$ dart run bin/profile.dart bin/workload_fast.dart
The Dart VM service is listening on http://127.0.0.1:56045/U-NptglKslI=/
200000 orders, 500 customers in 438 ms

35 samples, period 1000 us

Self time (function at the top of the stack):
   28.6%  [native] ZwWaitForAlertByThreadId
   22.9%  _RegExp._ExecuteMatch
    5.7%  _Double._toString
    5.7%  _GrowableList.length=
    5.7%  _GrowableList._allocateData
    5.7%  _ChunkedJsonParser.parseNumber

Total time (function anywhere on the stack):
   71.4%  main
   71.4%  <anonymous closure>
   71.4%  _RawReceivePort._handleMessage
   28.6%  [native] ZwWaitForAlertByThreadId
   22.9%  slugify
   22.9%  _CastListBase._CastListBase

The program is twice as fast, and slugify dropped from 64% to 23% of the samples. The profile is flatter now; the remaining time is spread over JSON encoding, parsing and list growth. With only 35 samples, small entries are noise. Also note _CastListBase._CastListBase next to slugify: the JIT inlines functions into each other, so an optimized frame can be attributed to a caller that looks unrelated. Treat a profile as a guide to where to look, then confirm with a benchmark. The obvious next step here would be to call slugify once per distinct customer name instead of once per order.

Grouping samples with UserTag

In a large program, the same library functions are called from many places. UserTag from dart:developer labels samples with what the program was doing at the time. A tag stays current until you switch to another one:

import 'dart:developer';

import 'workload.dart';

final parseTag = UserTag('parse');
final reportTag = UserTag('report');

void main() {
  final input = makeInput(200000);

  var previous = parseTag.makeCurrent();
  final orders = Timeline.timeSync('parseOrders', () => parseOrders(input));
  previous.makeCurrent();

  previous = reportTag.makeCurrent();
  final totals = Timeline.timeSync(
    'totalsByCustomer',
    () => totalsByCustomer(orders),
    arguments: {'orders': orders.length},
  );
  previous.makeCurrent();

  print('${orders.length} orders, ${totals.length} customers');
}

The tag breakdown printed by bin/profile.dart:

By user tag:
   28.1%  Default
    7.8%  parse
   63.4%  report

makeCurrent() returns the previous tag, so restore it when you're done, as above. A program can create at most UserTag.maxUserTags (64) tags, so create them once, as top-level final variables, not per request. In DevTools, the CPU Profiler has a filter to show only samples with a given tag, and an option to group the call tree by tag. Tags are cheap: switching the tag is a field write, so they can stay in production code.

The timeline

The CPU profiler shows statistics. The timeline shows events in time order: when each operation started and ended, which thread it ran on, and when the garbage collector ran. The program above already uses Timeline.timeSync, which records a span around a synchronous callback and returns its result.

For spans that don't fit into one callback use Timeline.startSync and Timeline.finishSync, and for asynchronous operations use TimelineTask, which can be started in one place and finished after any number of awaits:

import 'dart:developer';

Future<String> fetchUser(int id) async {
  final task = TimelineTask(filterKey: 'net')
    ..start('fetchUser', arguments: {'id': id});
  try {
    await Future<void>.delayed(Duration(milliseconds: 40 + id * 10));
    return 'user$id';
  } finally {
    task.finish();
  }
}

Future<void> main() async {
  Timeline.startSync('startup');
  final config = List.generate(100000, (i) => 'key$i=$i').join('\n');
  Timeline.finishSync();

  final users = await Future.wait([for (var i = 1; i <= 3; i++) fetchUser(i)]);
  print('${config.length} bytes of config, users: $users');
}

Every startSync needs a matching finishSync on the same isolate; use try/finally if the code between them can throw (see try, finally, and cleanup). arguments are attached to the event and shown in the details pane. When no tool is recording the Dart stream, these calls do almost nothing.

Viewing the timeline in DevTools

Run with --observe and open the Performance page. Your events appear in the Dart track next to GC events, and TimelineTasks appear as async tracks. The page embeds the Perfetto trace viewer: drag to zoom, click an event to see its duration and arguments. Use the gear icon to choose which streams are recorded; turning on GC is the quickest way to see whether garbage collection pauses explain a slow spot.

Recording a trace to a file

You don't need DevTools to record a trace. The file recorder writes a JSON file in the Chrome trace event format:

$ dart run --timeline-streams=Dart,GC --timeline-recorder=file:trace.json bin/tagged.dart
200000 orders, 500 customers

Open trace.json in https://ui.perfetto.dev or in chrome://tracing. With --timeline-recorder=perfettofile:trace.pftrace you get Perfetto's native binary format instead.

The file is easy to process. This script adds up the duration of every event name:

import 'dart:convert';
import 'dart:io';

/// Summarizes a Chrome-format trace written by --timeline-recorder=file.
void main(List<String> args) {
  final events = (jsonDecode(File(args.first).readAsStringSync()) as List)
      .cast<Map<String, dynamic>>();

  final open = <String, List<int>>{}; // span key -> start timestamps
  final totals = <String, (int count, int micros)>{};
  for (final e in events) {
    final ts = e['ts'] as int;
    // Sync spans (B/E) nest per thread; async spans (b/e) are matched by id.
    final key = e['id'] ?? '${e['tid']}/${e['name']}';
    switch (e['ph']) {
      case 'B' || 'b':
        open.putIfAbsent(key, () => []).add(ts);
      case 'E' || 'e':
        final start = open[key]?.removeLast();
        if (start == null) break;
        final label = '${e['cat']}: ${e['name']}';
        final (n, us) = totals[label] ?? (0, 0);
        totals[label] = (n + 1, us + ts - start);
    }
  }

  final sorted = totals.entries.toList()
    ..sort((a, b) => b.value.$2.compareTo(a.value.$2));
  print('${'event'.padRight(36)} count   total ms');
  for (final MapEntry(key: label, value: (n, us)) in sorted.take(8)) {
    final ms = (us / 1000).toStringAsFixed(1).padLeft(9);
    print('${label.padRight(36)} ${'$n'.padLeft(5)}  $ms');
  }
}
$ dart run bin/trace_summary.dart trace.json
event                                count   total ms
Dart: totalsByCustomer                   1      644.5
Dart: parseOrders                        1      106.8
GC: Scavenge                            48      106.2
GC: CollectNewGeneration                25       54.7
GC: ConcurrentMark                      12       34.7
GC: Sweep                               56       26.6
GC: IterateRememberedCards              48       23.9
GC: ConcurrentSweep                      4       22.5

Each event has a phase ph: B/E begin and end a synchronous span, b/e an async span with an id. The young-generation collector (Scavenge) ran 48 times for about 106 ms in total, which tells us the program allocates a lot of short-lived objects. Some GC work (ConcurrentMark, ConcurrentSweep) happens on helper threads and doesn't pause Dart code.

For the async example:

$ dart run --timeline-streams=Dart --timeline-recorder=file:async.json bin/async_trace.dart
1477779 bytes of config, users: [user1, user2, user3]
$ dart run bin/trace_summary.dart async.json
event                                count   total ms
Dart: fetchUser                          3      201.4
Dart: BinaryBuilder.readComponent        1       17.8
Dart: startup                            1       15.2
Dart: BinaryPrinter.writeComponentFile     1        0.3

The three fetchUser tasks overlapped, so their durations add up to more than the time the program waited. The BinaryBuilder events come from dart run loading the compiled program, not from your code.

Memory profiling

The DevTools Memory page has three tabs:

How the Dart heap and garbage collector work is covered in Memory and garbage collection.

Allocation profile from code

The VM service method behind Profile Memory is getAllocationProfile. A program can even start its own VM service with Service.controlWebServer and query itself, which is a quick way to look for a leak without any external tool:

import 'dart:developer';
import 'dart:isolate';

import 'package:vm_service/vm_service.dart' hide Isolate;
import 'package:vm_service/vm_service_io.dart';

class Session {
  final String id;
  final List<int> buffer;
  Session(this.id) : buffer = List.filled(256, 0);
}

final sessions = <String, Session>{}; // grows forever: a leak

void handleRequest(int i) {
  sessions['user-$i'] = Session('user-$i');
}

Future<void> main() async {
  // Start the VM service from inside the program and connect to it.
  final info = await Service.controlWebServer(enable: true, silenceOutput: true);
  final service = await vmServiceConnectUri(info.serverWebSocketUri.toString());
  final isolateId = Service.getIsolateId(Isolate.current)!;

  for (var round = 1; round <= 3; round++) {
    for (var i = 0; i < 20000; i++) {
      handleRequest(round * 100000 + i);
    }
    final profile = await service.getAllocationProfile(isolateId, gc: true);
    final usage = profile.memoryUsage!;
    print('round $round: heap used ${usage.heapUsage! ~/ 1024} KB');
    final top = profile.members!
        .where((m) => (m.bytesCurrent ?? 0) > 0)
        .toList()
      ..sort((a, b) => b.bytesCurrent!.compareTo(a.bytesCurrent!));
    for (final m in top.take(4)) {
      final kb = (m.bytesCurrent! ~/ 1024).toString().padLeft(7);
      print('  $kb KB ${m.instancesCurrent.toString().padLeft(7)}  ${m.classRef!.name}');
    }
  }

  await service.dispose();
  await Service.controlWebServer(enable: false);
}
$ dart run bin/memory.dart
round 1: heap used 53299 KB
    43468 KB   51846  _List
     1821 KB   51527  _OneByteString
     1338 KB   10710  Function
     1038 KB    2103  Instructions
round 2: heap used 97773 KB
    84923 KB   76593  _List
     3110 KB   92594  _OneByteString
     1558 KB   12470  Function
     1250 KB   40000  Session
round 3: heap used 140298 KB
   125553 KB   96631  _List
     4360 KB  132594  _OneByteString
     1875 KB   60000  Session
     1558 KB   12470  Function

gc: true runs a full garbage collection first, so only reachable objects are counted. The heap grows by about 44 MB per round and the Session count grows by exactly 20000 per round: nothing ever removes sessions. _List is the VM's fixed-length list class, which backs both each session's buffer and the map's storage. The class that leaks is often not the class that uses the most bytes; look for counts that keep growing, then use retaining paths in DevTools to find who holds them (here, the top-level sessions map).

The VM service, and with it getAllocationProfile, doesn't exist in AOT executables. The same program compiled with dart compile exe fails at vmServiceConnectUri with WebSocketException: Unsupported URL scheme '', because there is no service to connect to.

Writing a heap snapshot to a file

NativeRuntime.writeHeapSnapshotToFile from dart:developer writes a full heap snapshot without connecting to anything, for example from a signal handler or an admin endpoint of a server:

import 'dart:developer';
import 'dart:io';

final cache = <int, List<int>>{};

void main() {
  for (var i = 0; i < 10000; i++) {
    cache[i] = List.filled(100, i);
  }
  NativeRuntime.writeHeapSnapshotToFile('app.heapsnapshot');
  print('wrote ${File('app.heapsnapshot').lengthSync() ~/ 1024} KB');
}
$ dart run bin/snapshot.dart
wrote 5105 KB

$ dart compile exe bin/snapshot.dart -o snap.exe && ./snap.exe
Unhandled exception:
Unsupported operation: Heap snapshots are only supported in non-product mode.

The API is marked experimental. Like the VM service, it works in JIT mode (dart run) but not in AOT executables.

Profiling AOT and release builds

dart run profiles JIT-compiled code. That's usually what you want during development, but the AOT compiler optimizes differently: code that uses dynamic can be much slower in AOT, while JIT warm-up costs disappear. AOT executables made by dart compile exe run in product mode, without the VM service, so DevTools can't connect to them. To profile one:

Profiling tests and servers

Don't leave --observe on in production: the VM service can execute code in your process. If you must use it on a server, keep it bound to localhost (the default) and keep the auth codes enabled.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents