A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
The time.h header gives you access to the system clock, calendar time, and CPU time. time(NULL) returns the current Unix timestamp: seconds since January 1, 1970 UTC. clock() returns the CPU time consumed by your process. difftime computes the difference between two calendar times. strftime formats a broken-down time struct into a human-readable string. These four functions cover 90 percent of time-related needs in C programs.
#include <stdio.h>#include <time.h>int main(void) {time_t now = time(NULL);printf("Unix timestamp: %ld\n", (long)now);struct tm *local = localtime(&now);printf("Local time: %04d-%02d-%02d %02d:%02d:%02d\n",local->tm_year + 1900, local->tm_mon + 1, local->tm_mday,local->tm_hour, local->tm_min, local->tm_sec);char buf[64];strftime(buf, sizeof(buf), "%A, %B %d, %Y at %I:%M %p", local);printf("Formatted: %s\n", buf);return 0;}
tm_year is years since 1900, so add 1900. tm_mon is 0-based (0 = January), so add 1. These offsets are a historical artifact from the 1970s that every C programmer must remember. strftime handles the formatting with printf-like format codes: %Y for four-digit year, %m for zero-padded month, %d for day, %H for 24-hour, %I for 12-hour, %p for AM/PM.
#include <stdio.h>#include <time.h>long compute_sum(long n) {long sum = 0;for (long i = 0; i < n; i++) {sum += i;}return sum;}int main(void) {clock_t start = clock();long result = compute_sum(100000000L);clock_t end = clock();double cpu_seconds = (double)(end - start) / CLOCKS_PER_SEC;printf("Sum: %ld\n", result);printf("CPU time: %.4f seconds\n", cpu_seconds);return 0;}
clock() measures CPU time, not wall-clock time. If your process sleeps or waits for I/O, clock does not advance. For wall-clock elapsed time, use time(NULL) before and after, or better, clock_gettime(CLOCK_MONOTONIC) on POSIX for nanosecond resolution. CLOCKS_PER_SEC is typically 1000000 on Linux, giving microsecond granularity.
#include <stdio.h>#include <time.h>int main(void) {struct tm start_tm = {0};start_tm.tm_year = 2026 - 1900;start_tm.tm_mon = 0;start_tm.tm_mday = 1;time_t start = mktime(&start_tm);time_t now = time(NULL);double days = difftime(now, start) / 86400.0;printf("Days since Jan 1, 2026: %.1f\n", days);return 0;}
Time handling in C is mechanical but full of off-by-1900 traps. The functions are reliable. The struct fields are quirky. Memorize the offsets and move on. Next: sleep and usleep, for pausing execution with different granularities.
Finish the lesson once you have worked through the material. This awards ★ 30 XP.