Open In App

clock() function in C

The clock() function in C returns the approximate processor time that is consumed by the program which is the number of clock ticks used by the program since the program started.

The clock() time depends upon how the operating system allocates resources to the process that’s why clock() time may be slower or faster than the actual clock. The C clock() function is defined in the <ctime> header file.

The difference between the clock() value at the beginning of the program and the clock() value at the point where we want to measure the clock ticks is the number of clock ticks used by a program. The result can be converted to seconds using the CLOCKS_PER_SEC constant, which represents the number of clock ticks per second.

Syntax

clock_t clock( void );

Parameters

Return Value

C Program to Illustrate the use of clock() Function




// C Program to Illustrate the use of clock() Function
#include <math.h>
#include <stdio.h>
#include <time.h>
 
int main()
{
    float a;
    clock_t time_req;
 
    // Without using pow function
    time_req = clock();
    for (int i = 0; i < 200000; i++) {
        a = log(i * i * i * i);
    }
    time_req = clock() - time_req;
    printf("Processor time taken for multiplication: %f "
           "seconds\n",
           (float)time_req / CLOCKS_PER_SEC);
 
    // Using pow function
    time_req = clock();
    for (int i = 0; i < 200000; i++) {
        a = log(pow(i, 4));
    }
    time_req = clock() - time_req;
    printf("Processor time taken in pow function: %f "
           "seconds\n",
           (float)time_req / CLOCKS_PER_SEC);
 
    return 0;
}

Output

Processor time taken for multiplication: 0.005343 seconds
Processor time taken in pow function: 0.010641 seconds
Article Tags :