clock() function in C/C++

The clock() function is defined in the ctime header file. The clock() function returns the approximate processor time that is consumed by the program. The clock() time depends upon how the operating system allocate resources to the process that’s why clock() time may be slower or faster than the actual clock.

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 and on failure function returns -1.

Below program illustrates the implementation of clock() function:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to demonstrate
// example of clock() function.
  
#include<bits/stdc++.h>
using namespace std;
  
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;
    cout << "Processor time taken for multiplication: "
        << (float)time_req/CLOCKS_PER_SEC << " seconds" << endl;
  
    // Using pow function
    time_req = clock();
    for(int i=0; i<200000; i++)
    {
        a = log(pow(i, 4));
    }
    time_req = clock() - time_req;
    cout << "Processor time taken in pow function: "
        << (float)time_req/CLOCKS_PER_SEC << " seconds" << endl;
  
    return 0;
}

chevron_right


Output:

Processor time taken for multiplication: 0.006485 seconds
Processor time taken in pow function: 0.022251 seconds


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.