C++ clock()

In order to compute the processor time, the difference between values returned by two different calls to clock(), one at the start and other at the end of the program is used. To convert the value to seconds, it needs to be divided by a macro CLOCKS_PER_SEC.

The clock() time may advance faster or slower than the actual wall clock. It depends on how the operating system allocates the resources for the process.

If the processor is shared by other processes, the clock() time may advance slower than the wall clock. While if the current process is executed in a multithreaded system, the clock() time may advance faster than wall clock.


clock() prototype

clock_t clock();

It is defined in <ctime> header file.


clock() Parameters

  • None

clock() Return value

  • On success, the clock() function returns the processor time used by the program till now.
  • On failure, it returns -1 that is casted to the type clock_t.

Example: How clock() function works

#include <iostream>
#include <ctime>
#include <cmath>
using namespace std;

int main ()
{
	float x,y;
	clock_t time_req;

	// Using pow function
	time_req = clock();
	for(int i=0; i<100000; i++)
	{
		y = log(pow(i,5));
	}
	time_req = clock() - time_req;
	cout << "Using pow function, it took " << (float)time_req/CLOCKS_PER_SEC << " seconds" << endl;
	
	// Without pow function
	time_req = clock();
	for(int i=0; i<100000; i++)
	{
		y = log(i*i*i*i*i);
	}
	time_req = clock()- time_req;
	cout << "Without using pow function, it took " << (float)time_req/CLOCKS_PER_SEC << " seconds" << endl;

	return 0;
}

When you run the program, the output will be:

Using pow function, it took 0.014743 seconds

Without using pow function, it took 0.001357 seconds

Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges