C++ Standard Library C++ STL Library

C++ <ctime> - clock() Function



The C++ <ctime> clock() function returns the processor time consumed by the program. The returned value is expressed in clock ticks, which are units of time of a constant but system-specific length. Dividing a count of clock ticks by CLOCKS_PER_SEC yields the number of seconds.

The epoch used as reference by clock varies between systems, but it is related to the program execution. To calculate the actual processing time of a program, the value returned by clock shall be compared to a value returned by a previous call to the same function.

Syntax

clock_t clock ();

Parameters

No parameter is required.

Return Value

Returns number of clock ticks elapsed since an epoch related to the particular program execution. On failure, the function returns a value of -1.

Example:

The example below shows the usage of clock() function.

#include <iostream>
#include <ctime>
using namespace std;
 
int main (){
  clock_t start, finish;
  long product;

  start = clock();
  for(int i = 0; i < 100000; i++)
    for(int j = 0; j < 25000; j++) 
      product = i*j;

  finish = clock();

  //calculating the time difference
  //in ticks and in milliseconds
  cout<<"Time taken = "<<
        (finish - start)<<" ticks (" <<
        1000.0 * (finish - start)/CLOCKS_PER_SEC
        <<" milliseconds)";   
  return 0;
}

The possible output of the above code could be:

Time taken = 5591147 ticks (5591.15 milliseconds)

❮ C++ <ctime> Library