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.
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Practice Computer Science MCQs
- Apply for C Internship
- Practice BCA MCQs
- Watch Advanced C Programming Videos
- Buy Computer Science Books