How to measure time taken by function to execute Dart|Flutter measure

In this blog post, Dart offers ways to calculate measure (elapsed) time taken by a function execution.

Sometimes, we need to know function execution time while profiling a Dart application to improve performance.

It helps the developer to pinpoint the problem method for the time taken.

Time elapse taken in Dart. Measure execution time in Flutter.

Dart measure execution time

Dart provides a StopWatch class that calculates measure time. You can run StopWatch by calling the start method. stop() method to stop the execution. It provides various elapsed properties to return the time taken for execution

  • elapsed: return Duration Object that returns elapsed microseconds
  • elapsedMilliseconds : Returns elapsed milliseconds
  • elapsedMicroseconds: Returns elapsed microseconds
  • elapsedTicks : Elapsed number of ticks

Here is an example to measure the elapsed time taken for function execution

getData() {
  print("API data");
}

void main() {
  final stopwatch = Stopwatch()..start();
  getData();
  stopwatch.stop();
  print('Time taken to execute method: ${stopwatch.elapsed}');
}

Output:

API data
Time is taken to execute method: 0:00:00.000301

Execution time takes to execute in dart flutter web application

window.performance.now() can be used on a Web application that returns high-resolution time(nanoseconds etc). It returns microseconds in double format.

It returns the time elapsed since the time of origin Here is an example of usage

import 'dart:html';

getData() {
  print("API data");
}

void main() {
  var timer1 = window.performance.now();
  print(timer1); // 118.40000000037253

  getData();
  var timer2 = window.performance.now();

  print(timer2); // 118.59999999962747

  print('Time taken to execute method: ${timer2 - timer1}');
}

Output:

118.40000000037253
API data
118.59999999962747
Time is taken to execute method: 0.19999999925494194

Conclusion

In Dart, you can use a Stopwatch to measure function execution. use window.performance.now to get high-resolution time such as nanoseconds in Flutter and browser web applications.