Small Steps II — Making Things

Measuring elapsed time

Measure elapsed time.

What you will learn

StopWatch measures elapsed time. It starts when you create the object, and elapsed reports the seconds that have passed.

Try it

Example · example1.cpp
void small_main()
{
    StopWatch watch;

    sleep(1.0);
    print("About one second: ", watch.elapsed());

    watch.reset();
    sleep(0.5);
    print("About half a second: ", watch.elapsed());
}

After sleep(1.0), the result is about 1 second. After reset and sleep(0.5), it is about 0.5 seconds. Reading the watch does not reset it to zero; reset starts the measurement again.

It is normal for the execution environment to make the results differ from exactly 1.000 or 0.500.

Exercise

Create a StopWatch and print elapsed after sleep(2.0). A result other than exactly 2.000... is normal.

Exercise starter · exercise1_starter.cpp
void small_main()
{
    StopWatch watch;

    // Wait two seconds and print the elapsed time.
}

Hint

StopWatch starts when created, so it needs no separate start call.

show solution
void small_main()
{
    StopWatch watch;

    sleep(2.0);
    print("Elapsed: ", watch.elapsed());
}
← Previous lessonNext lesson →