Site Tools


h-time

Table of Contents

<time.h>

<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.

Example

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;
}

Common functions

Current time (seconds since epoch, 1970-01-01 00:00:00 UTC):

  • time(&t): get current wall-clock time (returns time_t, sets t if non-NULL)
  • clock(): get CPU time used by process (call twice and subtract to measure)

High-resolution time (POSIX, not standard C):

  • clock_gettime(clock_id, &timespec): high-resolution time with nanoseconds
  • CLOCK_REALTIME: wall-clock time
  • CLOCK_MONOTONIC: monotonic time (unaffected by system clock adjustments)

Time conversions (to/from struct tm):

  • localtime(&time_t): convert to local time struct (uses system timezone)
  • gmtime(&time_t): convert to UTC time struct
  • mktime(&tm): convert local time struct to time_t
  • localtime_r(&time_t, &tm): reentrant version of localtime (POSIX)
  • gmtime_r(&time_t, &tm): reentrant version of gmtime (POSIX)

Formatting time to string:

  • strftime(buf, size, fmt, &tm): format struct tm using format string
  • asctime(&tm): format as “Dow Mon DD HH:MM:SS YYYY\n” (deprecated)
  • ctime(&time_t): shorthand for asctime(localtime(t)) (deprecated)

Parsing time from string (POSIX):

  • strptime(str, fmt, &tm): parse string into struct tm

Time arithmetic:

  • difftime(t1, t2): seconds between t1 and t2

Types and constants:

  • time_t: time value (seconds since epoch)
  • struct tm: broken-down time (year, month, day, hour, minute, second, etc.)
  • struct timespec: time with nanosecond precision (tv_sec, tv_nsec)
  • CLOCKS_PER_SEC: conversion factor for clock() output to seconds
h-time.md · Last modified: by 127.0.0.1