<time.h> provides time functions: time() for wall-clock seconds since epoch, clock() for CPU time, struct tm for broken-down calendar time, and strftime() for formatting. Use clock_gettime(CLOCK_MONOTONIC, ...) for nanosecond-resolution wall-clock timing.
Note: struct tm fields like tm_mon are 0-indexed.
This example measures wall-clock and CPU time for a compute loop.
// compile: gcc -o timeexample timeexample.c // run: ./timeexample // description: measure CPU and wall-clock time for a loop #include <time.h> #include <stdio.h> int main() { struct timespec wall_start, wall_end; clock_t cpu_start, cpu_end; clock_gettime(CLOCK_MONOTONIC, &wall_start); cpu_start = clock(); volatile long sum = 0; for (long i = 0; i < 100000000L; i++) sum += i; cpu_end = clock(); clock_gettime(CLOCK_MONOTONIC, &wall_end); double wall = (wall_end.tv_sec - wall_start.tv_sec) + (wall_end.tv_nsec - wall_start.tv_nsec) * 1e-9; double cpu = (double)(cpu_end - cpu_start) / CLOCKS_PER_SEC; printf("wall: %.3f s, cpu: %.3f s\n", wall, cpu); return 0; }