<time.h> LibraryThe <time.h> library is C's standard interface for working with dates and times. It provides functions to fetch the current system time, calculate differences between timestamps, and measure the execution performance of your code.
time()The most fundamental time type in C is time_t. It typically represents the number of seconds that have elapsed since the "Unix Epoch" (January 1, 1970, 00:00:00 UTC).
The time() function returns this value.
#include <stdio.h> #include <time.h>int main() { time_t current_time; // Pass a pointer to the variable, or receive the return value current_time = time(NULL); printf("Seconds since January 1, 1970: %ld\n", current_time); return 0; }
ctime()While an integer representing seconds is useful for computers, humans prefer readable text. The ctime() function takes a pointer to a time_t variable and returns a string representing local time.
#include <stdio.h> #include <time.h>int main() { time_t now; time(&now); printf("Current Local Time: %s", ctime(&now)); return 0; }
clock()If you want to test how efficient an algorithm is, you can measure the CPU time it took to execute using the clock() function. It returns the number of clock ticks elapsed since the program was launched.
To convert this value into seconds, you must divide it by the macro CLOCKS_PER_SEC.
#include <stdio.h> #include <time.h>int main() { clock_t start_time, end_time; double time_taken; // Record start time start_time = clock(); // Perform a time-consuming task long long sum = 0; for(long long i = 0; i < 100000000; i++) { sum += i; } // Record end time end_time = clock(); // Calculate total time in seconds time_taken = ((double)(end_time - start_time)) / CLOCKS_PER_SEC; printf("Task completed. Sum: %lld\n", sum); printf("Execution time: %f seconds\n", time_taken); return 0; }