Welcome to our deep dive into C programming! Today, we're going to learn how to measure the execution time of our C programs. This skill is essential for optimizing your code and understanding its performance. 💡
Execution time refers to the duration it takes for a program to run from start to finish. In C, we can measure this time using functions like clock() and time().
The clock() function provides the clock ticks passed since the program started. The higher the number, the longer the program has run.
Here's a simple example:
#include <stdio.h>
#include <time.h>
int main() {
clock_t start = clock();
// Your code here
clock_t end = clock();
double time_taken = (double)(end - start) / CLOCKS_PER_SEC;
printf("Time taken: %.6f seconds\n", time_taken);
return 0;
}In this example, we measure the execution time of an empty program. Replace the comments with your own code to measure its execution time.
The time() function provides the time in seconds since the Epoch (January 1, 1970). This function is more useful for long-running programs or comparing the time between multiple runs.
#include <stdio.h>
#include <time.h>
int main() {
time_t start = time(NULL);
// Your code here
time_t end = time(NULL);
double time_taken = difftime(end, start);
printf("Time taken: %.6f seconds\n", time_taken);
return 0;
}Measuring execution time is useful in many situations. For instance, when optimizing a loop, or comparing the performance of different algorithms.
#include <stdio.h>
#include <time.h>
void my_function(int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += i;
}
}
int main() {
clock_t start, end;
double clock_time;
for (int n = 10000; n <= 1000000; n *= 10) {
start = clock();
my_function(n);
end = clock();
clock_time = (double)(end - start) / CLOCKS_PER_SEC;
printf("For array size %d: Execution time %.6f seconds\n", n, clock_time);
}
return 0;
}In this example, we measure the execution time of a simple function for different array sizes. This helps us understand how the function's performance changes with the size of the data.
By the end of this lesson, you should be able to measure the execution time of your C programs, helping you optimize your code and understand its performance better. Happy coding! 🎉