CodeBlanks Logo Icon CodeBlanks

Stopwatch

Learn time measurement with Stopwatch.

Stopwatch

Stopwatch is Dart's built-in timer class (in dart:core). It starts with start() and stops with stop(). elapsedMicroseconds gives the elapsed microseconds; elapsed gives a Duration.

Example: final sw = Stopwatch()..start(); /* work */ sw.stop(); print(sw.elapsedMicroseconds);. ..start() is the cascade operator; it creates the object and starts it at once. isRunning tells whether it is still running. Stopwatch measures the real time of a loop or operation; the result depends on the machine and load.

Timing a loop with Stopwatch

To time a loop, Stopwatch is started before the loop and stopped after. The elapsed time is printed. But the time is not deterministic; it depends on the machine and load. So in tests it is safer to print the deterministic result of the loop rather than the time itself.

Example: var sum = 0; for (var i = 0; i < 1000; i++) { sum += i; } print('Sum: $sum'); print('Running: ${sw.isRunning}');. Here sum (0+1+...+999 = 499500) is deterministic. sw.isRunning is always false after stop(). Together they show both that the timing happened and that the result is correct.

Practice A loop with Stopwatch

In main start the timer with final sw = Stopwatch()..start();. Write a for loop with var sum = 0;: i from 0 to 999 (exclusive 1000), sum += i. Then call sw.stop();. Print with print('Sum: $sum') and print('Running: ${sw.isRunning}').

Starter code

main.dart
void main() {
  // create and start the Stopwatch
  // compute sum in a 0..999 loop
  // stop the Stopwatch
  // print sum and timer status
}

Sample solution

main.dart
void main() {
  final sw = Stopwatch()..start();
  var sum = 0;
  for (var i = 0; i < 1000; i++) {
    sum += i;
  }
  sw.stop();
  print('Sum: $sum');
  print('Running: ${sw.isRunning}');
}

Expected output

Sum: 499500
Running: false

Questions and answers

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

1 Starting the Stopwatch

Question
final sw = Stopwatch()..____();
Answer
final sw = Stopwatch()..start();

Explanation: Stopwatch()..start() starts the timer.

2 What does a Stopwatch measure?

  • Memory
  • Time Correct answer
  • Disk
  • Network

Explanation: a Stopwatch measures time.

3 Match the Stopwatch parts

Term Meaning
start Starts
stop Stops
elapsed Elapsed
isRunning Is running

All lessons in Advanced