Dates, clocks, and measuring time
Separate calendar time, local display, processor time, elapsed duration, resolution, and C23 clock support.
In this chapter8 sections
“What date is it?” and “How long did this work take?” are different questions. A clock suitable for one may be unsuitable for the other. C supplies calendar and processor-time facilities, with availability and behavior that you must check before interpreting the result.
1. Name the time you need
Calendar time locates an instant on a calendar-related scale. Elapsed time measures a duration between events. Processor time measures execution resources used, so waiting can increase elapsed time without using the same amount of processor time. A time zone changes a calendar display; it is not another unit of elapsed duration.
A monotonic clock does not run backward under its stated contract. Calendar clocks can be adjusted. Resolution describes the granularity of reported readings; it does not prove accuracy, monotonicity, or that a small operation will produce a nonzero measured duration.
2. Calendar fields have conventions
A struct tm is a broken-down calendar representation. tm_year counts years since 1900, and tm_mon counts months from zero. Mixing these conventions with human date notation causes common off-by-one and year errors. The fixed-date example below focuses on formatting; it does not ask the system for the current date.
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main(void)
{
struct tm date = {
.tm_year = 2024 - 1900, .tm_mon = 0, .tm_mday = 2,
.tm_hour = 0, .tm_min = 0, .tm_sec = 0,
.tm_wday = 2, .tm_yday = 1, .tm_isdst = 0
};
char text[32];
size_t length = strftime(text, sizeof text, "%Y-%m-%d", &date);
if (length == 0) return EXIT_FAILURE;
assert(strcmp(text, "2024-01-02") == 0);
if (puts(text) == EOF) return EXIT_FAILURE;
return EXIT_SUCCESS;
}
strftime returns the number of stored characters excluding the terminating null when it succeeds. For this nonempty date format, treat zero as failure and do not print the buffer. In general, zero can also mean a legitimately empty expansion. Textual names can depend on LC_TIME. The example keeps the unchanged startup C locale and uses numeric date fields.
3. Check calendar acquisition and conversion
time returns a time_t calendar value and reports unavailability as (time_t)-1. Do not assume time_t always counts Unix seconds or has one fixed width. difftime computes a difference in seconds between valid calendar values; direct subtraction is not the portable substitute for an unknown representation.
gmtime and localtime convert calendar values and can fail. Their returned storage can be reused by later related calls, so copy needed results before another conversion overwrites them. mktime interprets a broken-down value as local time and can normalise fields. Daylight-saving transitions can create ambiguous or missing local times; a date string alone may not identify one instant.
4. Processor time is not a stopwatch for waiting
clock returns an approximation of processor time used by the program, or (clock_t)-1 when unavailable. To express a valid clock-tick difference in seconds, divide it by CLOCKS_PER_SEC using suitable arithmetic. Readings have range and wrap limits; a short interval may appear as zero. Before subtracting readings, establish the type’s usable range and the clock’s contract for the platform.
C17 requires the TIME_UTC base for timespec_get. A successful call fills seconds and nanoseconds for calendar time. It does not promise monotonic elapsed-time measurement. The probe below checks success and the specified nanosecond range, without predicting the current reading.
#include <assert.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
struct timespec now;
if (timespec_get(&now, TIME_UTC) != TIME_UTC) return EXIT_FAILURE;
assert(now.tv_nsec >= 0 && now.tv_nsec <= 999999999L);
return EXIT_SUCCESS;
}
5. Store the meaning along with the measurement
For logs, decide which time scale, zone, and format the record uses. For performance, choose a clock that measures the intended resource, perform enough work to exceed resolution, and account for measurement overhead. For deadlines, use the relevant API’s clock and wait contract. A number labelled “time” cannot communicate all those choices.
An operation waited for a file for two seconds. Must clock report two seconds of processor time?
Read the explanation
No. Waiting duration and processor time are different quantities. Select a suitable elapsed-time clock for the waiting question.
Primary references and further reading
- WG14 N1570 — public C11 draft: 7.27: C17-baseline time facilities.
- WG14 N3096 — public C23 draft: 7.29: C23 time additions and optional bases; not the final ISO publication.
Before you move on
- Calendar time, elapsed duration, and processor time answer different questions.
- Calendar fields, conversions, and formatting have conventions and failure cases.
- Clock availability, resolution, range, and monotonicity must be checked separately.
Keep these ideas separate
- Clock resolution / Clock accuracy
- Fine reported units alone do not establish accurate or monotonic measurements of the intended quantity.
Why might a program that waits for two seconds use much less than two seconds of processor time?
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- Always the calendar date as Unix seconds.
Calendar time and the representation of time_t are separate from clock’s interface.
- Processor time used by the program, rather than a general wall-clock stopwatch.
✓ Correct reasoning. Check availability and convert using CLOCKS_PER_SEC under the interface’s limits.
- The number of source lines executed.
Source-line counts are not the quantity reported by this clock interface.
C17
Ready for the next idea?
Mark this chapter as read whenever you feel ready.