by Dinesh Thakur Category: Function and Pointer

The clock function is used to determine the processor time in executing a program or part of a program. The header file <time.h> should be included in the program for its application. The function prototype is given below.

clock_t clock(void);

The function returns a value of type c1ock_t which should be divided by the value of the macro CLOCK_PER_SEC to obtain the processor time in seconds. The function clock () is called at the beginning of program and again at the end of the program and the difference between the values returned gives the time spent by processor on the program. Program provides an illustration. The program compares the time taken in integer addition with the time taken in addition of double numbers.

Illustrates the application of function clock ()

void main()
  double Dsum, x = 1.2;
  int sum;
  int i, n = 10000000;
    // Below is declaration of variables of type clock_t.
  clock_t Time1, Time2, Time3, Time4;
  Time1 =clock(); //Start recording time now
  printf ( "Time1 = %lf\n", (double)Time1/ (double)CLOCKS_PER_SEC);
  for ( i=0 ; i<n; i++) //A large loop
    sum +=1;
    Time2 =clock(); //record the time now (after the loop).
    printf("clock_per_sec = %d\n", CLOCKS_PER_SEC);
    printf("Time taken for loop 1 = %lf sec\n", (double)(Time2 - Time1) /(double) CLOCKS_PER_SEC );
    Time3 =clock(); //record time at beginning of second loop
    for ( i=0 ; i<n; i++)
       Dsum += x;
       Time4 =clock(); //record time at end
       printf("Time taken for loop 2 = %lf sec\n",(double)(Time4 -Time3)/(double)CLOCKS_PER_SEC );

Function clock () in C

The program compares the time spent in addition of integer numbers and addition of double numbers. The time spent on a single operation is extremely small, so we take a large number of them, i.e., 10000000 operations of each. On a 2.4 GHz processor the time taken by 10000000 operations of + operations on integers is 0.031 sec and on doubles is 0.125000 sec. The addition of a double number has taken time which is nearly 4 times the time taken for integer addition.

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles