Timers and Time Functions in UNIX/Linux
Time is a fundamental concept in operating systems. UNIX provides multiple APIs for obtaining the current time, measuring elapsed time, tracking CPU usage, formatting dates, and suspending execution for specified intervals.
Learning Objectives
- Understand different types of time in UNIX.
- Learn calendar time and process time.
- Measure elapsed and CPU time.
- Convert and format dates.
- Use POSIX timer APIs.
- Suspend program execution using sleep functions.
1. What is Time in UNIX?
UNIX represents time using standardized data types and system interfaces. Applications use time values to measure durations, schedule events, record timestamps, and synchronize operations.
Different APIs are available depending on whether an application needs calendar time, CPU time, or high-resolution timing.
2. Why is Time Important?
Many operating system services depend on accurate time measurement.
- Scheduling tasks
- Logging events
- Measuring execution time
- Timeout handling
- Performance analysis
- File timestamps
3. Types of Time in UNIX
| Type | Purpose |
|---|---|
| Calendar Time | Represents a date and time. |
| Process Time | Measures CPU time consumed by a process. |
| Elapsed Time | Measures real-world duration between events. |
| High-Resolution Time | Provides precise timing measurements. |
4. Calendar Time
Calendar time represents the current date and time. In UNIX, calendar time is commonly stored as the number of seconds that have elapsed since the UNIX Epoch.
5. UNIX Epoch
The UNIX Epoch is the reference point used for calendar time.
Many UNIX time-related functions return or manipulate values relative to this reference point.
6. Process Time
Process time measures the amount of CPU time consumed by a process while it executes. Unlike calendar time, process time does not include periods during which the process is not executing on the CPU.
7. Calendar Time vs Process Time
| Calendar Time | Process Time |
|---|---|
| Represents wall-clock time | Represents CPU usage |
| Advances continuously | Advances only while CPU is used |
| Used for timestamps | Used for performance measurement |
8. time_t Data Type
Most UNIX calendar-time functions use the time_t data type. It represents calendar time in a form suitable for time-related system interfaces.
9. Common Time Operations
10. Interview Questions
- What is the UNIX Epoch?
- What is calendar time?
- What is process time?
- What is the purpose of
time_t? - How does process time differ from calendar time?
- What types of time are commonly used in UNIX?
- Why is accurate time measurement important in operating systems?
11. time()
The time() function returns the current calendar time
as a value of type time_t.
The returned value represents the number of seconds elapsed since the
UNIX Epoch.
12. Parameters and Return Value of time()
| Parameter | Description |
|---|---|
| tloc | Optional pointer where the current time is stored. |
| NULL | No additional storage is requested. |
On success, time() returns the current calendar time as a
time_t value.
13. Example: Using time()
14. ctime()
The ctime() function converts a
time_t value into a human-readable character string.
15. Example: Using ctime()
16. gmtime()
The gmtime() function converts a
time_t value into a broken-down time represented as a
struct tm, using Coordinated Universal Time (UTC).
17. localtime()
The localtime() function converts a
time_t value into a broken-down time represented as a
struct tm, using the system's local time zone.
18. gmtime() vs localtime()
| gmtime() | localtime() |
|---|---|
| Uses UTC | Uses local time zone |
| No time-zone adjustment | Applies local time-zone rules |
| Suitable for UTC calculations | Suitable for user-facing displays |
19. asctime()
The asctime() function converts a
struct tm into a human-readable character string.
20. difftime()
The difftime() function computes the difference, in seconds, between two calendar time values.
21. Time Conversion Flow
22. Interview Questions
- What does
time()return? - What is the purpose of
ctime()? - What is the difference between
gmtime()andlocaltime()? - What data type does
gmtime()return? - What is the purpose of
asctime()? - How does
difftime()calculate elapsed time? - When should
gmtime()be preferred overlocaltime()?
23. struct tm
The struct tm data structure represents a calendar time
broken down into individual components such as year, month, day, hour,
minute, and second.
Functions such as gmtime() and
localtime() return a pointer to this structure.
24. Members of struct tm
| Member | Description |
|---|---|
| tm_sec | Seconds (0–60) |
| tm_min | Minutes (0–59) |
| tm_hour | Hours (0–23) |
| tm_mday | Day of month (1–31) |
| tm_mon | Month since January (0–11) |
| tm_year | Years since 1900 |
| tm_wday | Day of week (0–6, Sunday = 0) |
| tm_yday | Day of year (0–365) |
| tm_isdst | Daylight Saving Time indicator |
25. Visual Representation of struct tm
26. Accessing Members of struct tm
Notice that tm_year stores the number of years since 1900,
and tm_mon stores months in the range 0–11.
27. mktime()
The mktime() function converts a local broken-down time
(struct tm) into a calendar time
(time_t).
28. Example: Using mktime()
The example creates a calendar time corresponding to the specified local date and time.
29. strftime()
The strftime() function formats a
struct tm into a character string according to a specified
format.
30. Common strftime() Format Specifiers
| Specifier | Description |
|---|---|
| %Y | Four-digit year |
| %m | Month (01–12) |
| %d | Day of month |
| %H | Hour (24-hour clock) |
| %M | Minute |
| %S | Second |
| %A | Full weekday name |
| %B | Full month name |
31. Example: Formatting Date and Time
32. Time Formatting Flow
33. Interview Questions
- What is the purpose of
struct tm? - Why is
tm_yearstored as years since 1900? - Why does
tm_monrange from 0 to 11? - What does
mktime()return? - What is the purpose of
strftime()? - Name four commonly used
strftime()format specifiers. - What is the difference between
ctime()andstrftime()?
34. gettimeofday()
The gettimeofday() function retrieves the current
calendar time with microsecond resolution.
Historically, it has been widely used in UNIX systems for measuring
elapsed wall-clock time. Modern POSIX applications often prefer
clock_gettime() for new development.
35. struct timeval
The struct timeval structure stores calendar time with
microsecond precision.
| Member | Description |
|---|---|
| tv_sec | Seconds since the UNIX Epoch |
| tv_usec | Microseconds (0–999999) |
36. Example: Using gettimeofday()
37. clock_gettime()
The clock_gettime() function retrieves time from a specified POSIX clock with nanosecond resolution. It is the preferred interface for precise time measurements.
38. struct timespec
The struct timespec structure stores time with nanosecond
precision.
| Member | Description |
|---|---|
| tv_sec | Seconds |
| tv_nsec | Nanoseconds (0–999999999) |
39. Common POSIX Clock IDs
| Clock ID | Purpose |
|---|---|
| CLOCK_REALTIME | Current system calendar time |
| CLOCK_MONOTONIC | Monotonic elapsed time that is not affected by setting the system clock |
40. Example: Using clock_gettime()
41. High-Resolution Time Flow
42. Interview Questions
- What is the purpose of
gettimeofday()? - What information is stored in
struct timeval? - Why is
clock_gettime()preferred for precise timing? - What is the difference between
struct timevalandstruct timespec? - When should
CLOCK_MONOTONICbe used instead ofCLOCK_REALTIME? - What resolution does
clock_gettime()provide?
43. times()
The times() function measures the CPU time consumed by
the calling process and its terminated child processes.
Unlike time(), which returns calendar time,
times() measures processor usage.
44. struct tms
The struct tms structure stores CPU usage information for
the calling process and its terminated child processes.
45. Members of struct tms
| Member | Description |
|---|---|
| tms_utime | User CPU time of the calling process |
| tms_stime | System CPU time of the calling process |
| tms_cutime | User CPU time of terminated child processes |
| tms_cstime | System CPU time of terminated child processes |
46. CPU Time Categories
The operating system separately tracks the amount of CPU time spent executing user code and kernel code.
47. Example: Using times()
48. clock()
The clock() function returns the amount of processor time consumed by the calling program. It is commonly used for measuring program execution time.
49. Example: Using clock()
50. time() vs times() vs clock()
| Function | Measures |
|---|---|
| time() | Calendar (wall-clock) time |
| times() | Process and child CPU usage |
| clock() | CPU time consumed by the calling program |
51. CPU Time Measurement Flow
52. Interview Questions
- What is the purpose of
times()? - What information is stored in
struct tms? - What is the difference between user CPU time and system CPU time?
- When should
clock()be used? - How does
clock()differ fromtime()? - What is measured by
tms_cutime? - Why does
times()return information about child processes?
53. sleep()
The sleep() function suspends the execution of the calling process for a specified number of seconds. If the requested interval completes without interruption, execution resumes after the specified number of seconds.
54. Return Value of sleep()
If the requested sleep interval completes successfully,
sleep() returns 0.
If the process is interrupted by a signal before the interval expires,
the function returns the number of whole seconds remaining.
55. Example: Using sleep()
56. sleep() Execution Flow
57. nanosleep()
The nanosleep() function suspends execution for a
specified interval with nanosecond precision.
It provides finer control over sleep durations than
sleep().
58. Parameters of nanosleep()
| Parameter | Description |
|---|---|
| req | Requested sleep interval |
| rem | Remaining time if interrupted by a signal |
59. Example: Using nanosleep()
60. sleep() vs nanosleep()
| sleep() | nanosleep() |
|---|---|
| Seconds only | Seconds and nanoseconds |
| Coarse precision | High precision |
| Simple delays | Precise timing applications |
| Returns remaining whole seconds if interrupted | Can report the remaining unslept interval through rem |
61. Interrupted Sleep
A sleeping process may be awakened before the requested interval has elapsed if a signal is delivered. Applications that require the full delay should check the return value and, when appropriate, continue sleeping for the remaining interval.
62. Interview Questions
- What is the purpose of
sleep()? - What does
sleep()return if interrupted? - How does
nanosleep()differ fromsleep()? - What is stored in the
remparameter ofnanosleep()? - Why is
nanosleep()preferred for high-precision delays? - Can a sleeping process be interrupted by a signal?
- When should an application resume sleeping after interruption?
63. alarm()
The alarm() function schedules the delivery of the SIGALRM signal to the calling process after a specified number of seconds. It is commonly used to implement execution time limits and timeout mechanisms.
64. Return Value of alarm()
The alarm() function returns the number of seconds
remaining from any previously scheduled alarm.
If no previous alarm is pending, the function returns
0.
Only one alarm can be active for a process at any given time. Scheduling a new alarm replaces the previous one.
65. Example: Using alarm()
66. alarm() Execution Flow
67. Canceling an Alarm
An active alarm can be canceled by calling
alarm(0).
Calling alarm(0) removes any pending alarm and prevents
the associated SIGALRM signal from being generated.
68. alarm() vs sleep()
| alarm() | sleep() |
|---|---|
| Schedules SIGALRM | Suspends execution |
| Does not block execution | Blocks the calling thread |
| Used for timeouts | Used for delays |
| Application continues until the signal is delivered | Application resumes only after the sleep interval expires or is interrupted |
69. Typical Uses of alarm()
- Implementing timeout mechanisms.
- Limiting execution time of operations.
- Interrupting long-running system calls.
- Periodic signal generation when combined with signal handlers.
70. alarm() Lifecycle
71. Interview Questions
- What is the purpose of
alarm()? - Which signal is generated by
alarm()? - How many active alarms can a process have?
- How can an existing alarm be canceled?
- What does
alarm()return? - How does
alarm()differ fromsleep()? - When is
alarm()commonly used?
72. Interaction Between alarm() and sleep()
Both alarm() and sleep() use timer facilities
provided by the operating system.
Historically, the implementation of sleep() on some UNIX
systems was based on SIGALRM and alarm().
Modern implementations may use different mechanisms internally.
Applications should avoid assuming that alarm() and
sleep() are completely independent.
73. Choosing the Appropriate Time Function
| Requirement | Recommended Function |
|---|---|
| Current calendar time | time() |
| Formatted date and time | strftime() |
| Broken-down local time | localtime() |
| Broken-down UTC time | gmtime() |
| Process CPU usage | times() |
| Program CPU time | clock() |
| High-resolution elapsed time | clock_gettime() |
| Simple delay | sleep() |
| Precise delay | nanosleep() |
| Timeout using signals | alarm() |
74. Best Practices
- Choose the API based on the type of time being measured.
- Use
clock_gettime()for high-resolution measurements. - Use
CLOCK_MONOTONICwhen measuring elapsed time. - Use
strftime()instead of manually formatting dates. - Check return values of all time-related functions.
- Use
nanosleep()when sub-second precision is required. - Use
alarm()only when signal-based timeouts are appropriate.
75. Common Programming Mistakes
| Mistake | Possible Result |
|---|---|
Using time() for performance benchmarking |
Low timing precision |
Using CLOCK_REALTIME for elapsed time measurements |
Incorrect results if the system clock changes |
| Ignoring interrupted sleep operations | Shorter delays than expected |
| Forgetting that only one alarm is active per process | Previously scheduled alarm is replaced |
| Not checking function return values | Undetected runtime errors |
76. Complete UNIX Time Function Comparison
| Function | Primary Purpose |
|---|---|
| time() | Current calendar time |
| ctime() | Convert time_t to readable string |
| gmtime() | Convert to UTC broken-down time |
| localtime() | Convert to local broken-down time |
| asctime() | Convert struct tm to readable string |
| mktime() | Convert local struct tm to time_t |
| strftime() | Format date and time |
| times() | Process CPU accounting |
| clock() | Program CPU time |
| gettimeofday() | Calendar time with microsecond resolution |
| clock_gettime() | High-resolution POSIX clock |
| sleep() | Delay execution |
| nanosleep() | High-precision delay |
| alarm() | Generate SIGALRM after a specified interval |
77. Selecting the Appropriate Time Function
78. Interview Questions
- Why should
CLOCK_MONOTONICbe preferred when measuring elapsed time? - Which function should be used for formatting dates?
- Why is
clock_gettime()preferred overgettimeofday()for precise measurements? - Can more than one alarm be active for a process?
- When should
times()be used instead ofclock()? - Which API should be selected for implementing a timeout?
- Why is checking return values important for time-related APIs?
80. Concepts Covered
- Time in UNIX
- Calendar Time
- Process Time
- UNIX Epoch
time_ttime()ctime()gmtime()localtime()asctime()difftime()struct tmmktime()strftime()gettimeofday()struct timevalclock_gettime()struct timespecCLOCK_REALTIMECLOCK_MONOTONICtimes()struct tmsclock()sleep()nanosleep()alarm()
81. Key Takeaways
- Calendar time represents real-world date and time.
- Process time measures CPU usage rather than elapsed time.
time_tstores calendar time values.struct tmstores broken-down calendar time.strftime()provides flexible date and time formatting.clock_gettime()provides high-resolution POSIX timing.CLOCK_MONOTONICis suitable for measuring elapsed intervals.times()andclock()measure CPU usage.sleep()andnanosleep()suspend execution.alarm()schedules the delivery ofSIGALRM.
82. Complete Time API Review
| API | Primary Purpose |
|---|---|
time() |
Get current calendar time |
ctime() |
Convert calendar time to a readable string |
gmtime() |
Convert calendar time to UTC |
localtime() |
Convert calendar time to local time |
asctime() |
Convert struct tm to a readable string |
mktime() |
Convert local broken-down time to calendar time |
strftime() |
Format date and time |
times() |
Measure process CPU usage |
clock() |
Measure CPU time consumed by the program |
gettimeofday() |
Retrieve current time with microsecond resolution |
clock_gettime() |
Retrieve high-resolution POSIX clock values |
sleep() |
Suspend execution for seconds |
nanosleep() |
Suspend execution with nanosecond precision |
alarm() |
Schedule delivery of SIGALRM |
83. Advanced Interview Questions
- Differentiate calendar time, elapsed time, and process CPU time.
- Why is the UNIX Epoch used as the reference point for calendar time?
- Explain the purpose of
time_tandstruct tm. - Compare
gmtime(),localtime(), andmktime(). - How does
strftime()differ fromctime()? - When should
CLOCK_MONOTONICbe preferred overCLOCK_REALTIME? - What information is stored in
struct timevalandstruct timespec? - Explain the difference between
times()andclock(). - How does
nanosleep()improve uponsleep()? - Describe how
alarm()is used to implement timeouts. - Why can only one alarm be active for a process?
- How can interrupted sleep operations be handled correctly?
- Which APIs are best suited for benchmarking program execution?
- Why is choosing the appropriate clock source important in POSIX programming?
- Explain a practical scenario where multiple time-related APIs are used together.
Concept Mastery Assessment — Module 22
Verify your conceptual understanding with 12 targeted technical assessment questions. Instant feedback and explanations are provided for every choice.