clock() function in C++

In this guide, you will learn what is clock() function is in C++ programming and how to use it with an example.

1. clock() Function Overview

The clock() function in C++ returns the processor time consumed by the program. It is defined in the <ctime> header file. The value returned by clock() is the number of clock ticks since the program was launched. To convert this value into seconds, it is typically divided by a constant, CLOCKS_PER_SEC.

Signature:

clock_t clock(void);

Parameters:

- No parameters.

2. Source Code Example

#include <iostream> #include <ctime> int main() { // Capture the start time clock_t start = clock(); // A simple loop to cause a delay and consume processor time for(long i = 0; i < 100000000; i++); // Capture the end time clock_t end = clock(); // Calculate time taken by the loop in seconds double duration = (double)(end - start) / CLOCKS_PER_SEC; std::cout << "Time taken by loop: " << duration << " seconds" << std::endl; return 0; } 

Output:

Time taken by loop: [Varies based on system and load, e.g., "0.28 seconds"] 

3. Explanation

1. clock() is called before and after a loop that consumes some processor time.

2. The difference between the two times represents the time taken by the loop.

3. This difference is divided by CLOCKS_PER_SEC to convert it into seconds.

4. The result is printed to the console, showing the time taken by the loop in seconds.


Comments