Welcome to our deep dive into the time() function in C programming! This function is a powerful tool that allows you to measure the elapsed time in seconds since the system started. Let's get started! šÆ
time() FunctionThe time() function is a part of the standard library in C programming. It returns the current time in seconds since January 1, 1970, 00:00:00 (known as the Unix Epoch).
#include <stdio.h>
#include <stdlib.h> // for time_t data type
int main() {
time_t current_time = time(NULL);
printf("Current time: %ld\n", current_time);
return 0;
}š Note: The time() function returns a time_t data type, which is an integer representing the number of seconds since the Unix Epoch.
One of the primary uses of the time() function is to measure the execution time of a piece of code. Here's an example:
#include <stdio.h>
#include <stdlib.h>
int factorial(int n) {
if (n <= 1)
return 1;
return n * factorial(n - 1);
}
int main() {
int number = 10;
double start = time(NULL);
int result = factorial(number);
double end = time(NULL);
printf("Factorial of %d is: %d\n", number, result);
printf("Time taken to calculate: %.5f seconds\n", end - start);
return 0;
}š” Pro Tip: Use double for the start and end times to get a more accurate measurement.
What does the `time()` function return in C programming?