Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Measuring elapsed time

To time how long something takes, do not subtract two readings of the wall clock: the operating system corrects it and users change it, so it can jump backwards. A Stopwatch reads a clock that only moves forward.

#import "std/chrono"

function SumTo( byval n as int64 ) as int64
    dim as int64 total = 0
    for i as int64 = 1 to n
        total += i
    next
    return total
end function

'' A Stopwatch reads a clock that only moves forward.
var sw = chrono.Stopwatch.StartNew( )
var total = SumTo( 1000000 )
var taken = sw.Elapsed

'' The time differs on every run; these facts do not.
print "total:"; total
print "running: "; sw.IsRunning
print "elapsed >= 0: "; cbool( taken.Ticks >= 0 )
print "a later reading is not smaller: "; ( sw.Elapsed >= taken )

'' Stop_ pauses it: time spent stopped is not counted.
sw.Restart( )
sw.Stop_( )
var paused = sw.ElapsedTicks
sleep 200, 1
print "stopped, so unchanged: "; cbool( sw.ElapsedTicks = paused )
print "running: "; sw.IsRunning

Output

total: 500000500000
running: true
elapsed >= 0: true
a later reading is not smaller: true
stopped, so unchanged: true
running: false

Stopwatch.StartNew( ) makes a running stopwatch. Elapsed is a TimeSpan; ElapsedMilliseconds and ElapsedTicks are numbers. Restart( ) zeroes it and keeps it running, Reset( ) zeroes and stops it, and Start( ) resumes. Stop_( ) has a trailing underscore because stop is a statement. A stopwatch adds up only the time it was running, so the sleep while it was stopped is not counted.

The time taken differs on every run and every machine, so the example prints facts about it rather than the time. For a real measurement, run the work several times, keep the fastest, and build with optimisation on.

chrono.CpuClock.ProcessTime( ) is the other clock worth knowing: the processor time the program has used, which a sleep does not add to.

Activities

  1. Time SumTo( 10000000 ) and print the result with TotalMilliseconds.
  2. Stop the stopwatch, sleep, start it again, and check that IsRunning is true and the paused time is still not counted.