Easy Tutorial
❮ C Examples Leap Year C Function Strspn ❯

C Library Function - clock()

C Standard Library - <time.h>

Description

The C library function clock_t clock(void) returns the processor time consumed by the program since its inception (typically at the beginning of the program). To obtain the number of seconds used by the CPU, you need to divide by CLOCKS_PER_SEC.

On a 32-bit system, CLOCKS_PER_SEC equals 1000000, and this function will return the same value approximately every 72 minutes.

Declaration

Here is the declaration for the clock() function.

clock_t clock(void)

Parameters

Return Value

This function returns the processor time used since the start of the program. If it fails, it returns a value of -1.

Example

The following example demonstrates the use of the clock() function.

#include <time.h>
#include <stdio.h>

int main()
{
   clock_t start_t, end_t;
   double total_t;
   int i;

   start_t = clock();
   printf("Program started, start_t = %ld\n", start_t);

   printf("Starting a big loop, start_t = %ld\n", start_t);
   for(i=0; i< 10000000; i++)
   {
   }
   end_t = clock();
   printf("Big loop ended, end_t = %ld\n", end_t);

   total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
   printf("Total CPU time used: %f\n", total_t  );
   printf("Exiting program...\n");

   return(0);
}

Let's compile and run the above program, which will produce the following result:

Program started, start_t = 2614
Starting a big loop, start_t = 2614
Big loop ended, end_t = 28021
Total CPU time used: 0.025407
Exiting program...

C Standard Library - <time.h>

❮ C Examples Leap Year C Function Strspn ❯