Provides types and functions to work with calendar time and CPU time. Key types: time_t (seconds since epoch) and struct tm (broken-down calendar time).
Include: #include <time.h> | Compile: gcc -Wall -o prog prog.c
| Name | Prototype / Value | Description |
|---|---|---|
| time | time_t time(time_t *t) | Return current calendar time (Unix epoch) |
| clock | clock_t clock(void) | Return processor time used by program |
| difftime | double difftime(time_t t2, time_t t1) | Difference t2 - t1 in seconds |
| mktime | time_t mktime(struct tm *tm) | Convert struct tm to time_t |
| gmtime | struct tm *gmtime(const time_t *t) | Convert time_t to UTC struct tm |
| localtime | struct tm *localtime(const time_t *t) | Convert time_t to local struct tm |
| asctime | char *asctime(const struct tm *tm) | Convert struct tm to readable string |
| ctime | char *ctime(const time_t *t) | Convert time_t to local time string |
| strftime | size_t strftime(char *s, size_t max, const char *fmt, const struct tm *tm) | Format time into string |
Copy, save as demo.c, and compile with the command shown at the bottom.
#include <stdio.h>
#include <time.h>
int main(void) {
time_t now = time(NULL);
struct tm *lt = localtime(&now);
char buf[64];
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", lt);
printf("Local time : %s\n", buf);
const char *days[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
printf("Day : %s\n", days[lt->tm_wday]);
clock_t start = clock();
volatile long sum = 0;
for (long i = 0; i < 100000000L; i++) sum += i;
double elapsed = (double)(clock() - start) / CLOCKS_PER_SEC;
printf("Loop took : %.4f seconds\n", elapsed);
return 0;
}
/* Compile: gcc -Wall -O2 -o time_demo time_demo.c */