Open In App
Related Articles

clock() function in C

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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

  • This function does not accept any parameter.

Return Value

  • This function returns the approximate processor time that is consumed by the program.
  • This function returns -1 in case of failure.

C Program to Illustrate the use of clock() Function

C

// 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


Last Updated : 06 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads