executionDuration static method

Future<Duration> executionDuration(
  1. FutureOr<void> task()
)

Calculates the execution duration of a task, accommodating both synchronous and asynchronous operations.

This method starts a stopwatch before the provided task begins, then stops it once the task completes (either synchronously or when the future resolves). It returns the elapsed time as a Duration.

Examples:

// Measuring a synchronous task
Duration syncDuration = await TimeUtils.executionDuration(() {
  // Perform some synchronous work here
  for (var i = 0; i < 1000000; i++) {}
});
print('Synchronous task took $syncDuration');

// Measuring an asynchronous task
Duration asyncDuration = await TimeUtils.executionDuration(() async {
  // Perform some asynchronous work here (e.g., network request)
  await Future.delayed(Duration(seconds: 2));
});
print('Asynchronous task took $asyncDuration');

Implementation

static Future<Duration> executionDuration(
  FutureOr<void> Function() task,
) async {
  final stopwatch = Stopwatch()..start();
  await task(); // Await if the task is a future
  stopwatch.stop();
  return stopwatch.elapsed;
}