w3resource

C clock() function

C clock() function - Report CPU time used

The clock() function is used to get the processor time used by the process since the beginning of an implementation-defined era related only to the process invocation.

Syntax:

clock_t clock(void)

Parameters:

Not available

Return value from clock() function

  • If the value of the processor time is not available or cannot be represented, the clock() function returns the value (clock_t)-1.

Example: clock() function

Following function prints the time that has elapsed since the program was invoked:

#include <time.h>
#include <stdio.h>
 
double time1, time_diff;   
 
int main(void)
{
    int n;
 
    time1 = (double) clock();  // get initial time 
    time1 = time1 / CLOCKS_PER_SEC;  // in seconds
 
    /* Running the FOR loop 100000000 times */
    for (n=0; n<100000000; n++);
 
    /* call clock a second time */
    time_diff = (((double) clock()) / CLOCKS_PER_SEC) - time1;
    printf("The elapsed time is %lf seconds\n", time_diff);
}

Output:

The elapsed time is 0.144000 seconds

C Programming Code Editor:

Previous C Programming: C asctime()
Next C Programming: C ctime()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming/time/c-clock.php