clock() Function in C

Question: What is Processor Time Function in Standard C Library?

Answer: ‘time.h’ header provides a time function that returns amount of processor time used by the program since it began executing. Though this is just an approximation. If more precise time estimation is required, call the ‘clock()’ function at the beginning of main() and subtract the value obtained there from value returned from a later call to ‘clock()’. Prototype of the function is written below

    clock_t clock(void);

Let’s estimate processor time used by a simple C program below,

/* processor_time.c -- program displays amount of processor time */
/* used by the program */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define COUNT 1000000000
int main(void)
    clock_t tm1, tm2;
    long i;
    /* called clock() at the start of program */
    tm1 = clock();
    /* here, most of processor's time consumed */
    for (i = 1; i < COUNT; i++);
    tm2 = clock();
    printf("amount of processor time: %d ticks and %d seconds\n",
                         (tm2 - tm1), (tm2 - tm1) / CLOCKS_PER_SEC);
    return 0;

Observe the output below

amount of processor time: 3130000 ticks and 3 seconds

Notice that ‘clock()’ returns a number which is usually number of times processor’s clock has ticked. It returns -1 if value returned is too large to be represebted as ‘clock_t’ variable or if implementation can’t provide it. To convert this amount into seconds, divide this by #defined symbol CLOCKS_PER_SEC. Further notice that it might be that your implementation isn’t able to track processor time, probably host system then gives real time that has elasped.

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

If you find any mistake above, kindly email to [email protected]

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.