C Program to calculate the total execution time of a program

Here is a C program that calculates the total execution time of a program:

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

int main() {
    clock_t start, end;
    double cpu_time_used;

    start = clock(); // Record the start time

    // Your program code goes here

    end = clock(); // Record the end time

    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC; // Calculate the total execution time in seconds

    printf("Total execution time: %f seconds\n", cpu_time_used);

    return 0;
}

Explanation of the steps:

  1. Include necessary header files:
  2. stdio.h for input/output operations.
  3. time.h for time-related functions.

  4. Declare variables:

  5. clock_t start, end; to store the start and end times of the program execution.
  6. double cpu_time_used; to store the total execution time in seconds.

  7. Record the start time:

  8. start = clock(); records the current value of the clock, which represents the number of clock ticks since the program started.

  9. Your program code:

  10. Replace the comment // Your program code goes here with your actual program code that you want to measure the execution time for.

  11. Record the end time:

  12. end = clock(); records the current value of the clock after your program code has finished executing.

  13. Calculate the total execution time:

  14. cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC; calculates the difference between the end time and the start time, then divides it by CLOCKS_PER_SEC to convert it into seconds.

  15. Print the total execution time:

  16. printf("Total execution time: %f seconds\n", cpu_time_used); displays the total execution time in seconds.

  17. Return from the main function:

  18. return 0; indicates successful program execution.

This program uses the clock() function from the time.h header to measure the execution time. The clock() function returns the number of clock ticks elapsed since the program started. By calculating the difference between the start and end times and dividing it by CLOCKS_PER_SEC, we can obtain the execution time in seconds.