Site Tools


wiki:time.h

Table of Contents

time.h

Getting the current time is a one-liner. Timing how long something takes, converting between timezones, or formatting a timestamp all have more moving parts than you would expect. time.h provides the types and functions for all of it: time_t (seconds since the Unix epoch), struct tm (broken-down calendar time), and clock_t (CPU time).

#include <time.h>
#include <stdio.h>
 
time_t now = time(NULL);
struct tm *local = localtime(&now);
 
printf("%04d-%02d-%02d\n",
       local->tm_year + 1900,
       local->tm_mon + 1,    // tm_mon is 0-indexed
       local->tm_mday);

struct tm fields: tm_sec (0-60), tm_min (0-59), tm_hour (0-23), tm_mday (1-31), tm_mon (0-11), tm_year (years since 1900), tm_wday (0=Sunday), tm_yday (0-365), tm_isdst (DST flag).

Converting between representations:

// broken-down → time_t
time_t t = mktime(tm_ptr);
 
// formatted string
char buf[64];
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", local);
 
// string → broken-down (POSIX, not strictly standard C)
strptime("2025-01-15", "%Y-%m-%d", &tm);

clock() measures CPU time consumed by the process, not wall-clock time. On a multi-threaded program it may advance faster than real time. For wall-clock timing at higher resolution, use clock_gettime(CLOCK_MONOTONIC, &ts) — it returns nanosecond-resolution monotonic time that does not jump when the system clock is adjusted.

Practice

// compile: gcc -o timedemo timedemo.c
// run: ./timedemo
// description: measure wall-clock and CPU time for a compute loop
 
#include <time.h>
#include <stdio.h>
 
int main(void) {
    struct timespec wall_start, wall_end;
    clock_t cpu_start, cpu_end;
 
    clock_gettime(CLOCK_MONOTONIC, &wall_start);
    cpu_start = clock();
 
    // busy work
    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\n", wall);
    printf("cpu:  %.3f s\n", cpu);
    printf("sum:  %ld\n", sum);
    return 0;
}

On a single-threaded process, wall and CPU time should be close. Replace CLOCK_MONOTONIC with CLOCK_PROCESS_CPUTIME_ID to get CPU time via clock_gettime at nanosecond resolution, which is more precise than clock().

wiki/time.h.md · Last modified: by 127.0.0.1