C++ || Snippet – Simple Timer Class Using The Clock Function

Print Friendly, PDF & Email

The following is sample code for a simple timer class using the “clock()” function. The “clock” function returns the processor time that has been consumed by the program during its execution; or in other words, it returns the number of clock ticks that has elapsed since the program was launched.

The timer class demonstrated on this page has the ability to measure the execution time of a block of code or function call, and display the elapsed running time (in seconds) to the screen.

Unfortunately, by using the clock() function (instead of date based methods) to measure time, this class is only able to measure the time that was actually spent used by the CPU during the execution of the program. That means that if this timer class was used to measure how long it took for a user to enter data into the program, the users CPU wouldn’t notice any change in time, and this timer class would display that 0 seconds had elapsed.

However, by using the clock() function to measure elapsed time, it can be used to implement a simple and portable timer.


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

===== DEMONSTRATION HOW TO USE =====

Use of the above class is very simple to use. Here are sample programs demonstrating its use.


SAMPLE OUTPUT:

Starting the timer..
Timer stopped!

It took 3749 clicks (3.749 seconds)

SAMPLE OUTPUT:

How many seconds do you want to sleep?: 5

Starting the timer..
0
1
2
3
4

Timer stopped!

It took 5000 clicks (5 seconds)

Leave a Reply