Linux 时间编程基础
Linux 时间编程是系统开发中的重要组成部分,涉及时间的获取、转换、格式化以及定时任务等多个方面,Linux 系统提供了丰富的 API 和工具,支持多种时间表示方式,如日历时间(Calendar Time)、进程时间(Process Time)以及高精度时间(High-Resolution Time),本文将详细介绍 Linux 时间编程的核心概念、常用函数及实践应用。

时间表示方式
Linux 中时间主要通过以下几种方式表示:
- 日历时间:自 1970 年 1 月 1 日 00:00:00 UTC(称为 Unix 纪元)以来经过的秒数,用
time_t类型存储。time()函数返回当前时间的time_t值。 - 分解时间:将日历时间分解为年、月、日、时、分、秒等结构体,用
struct tm表示,该结构体定义在<time.h>中,包含tm_year、tm_mon、tm_mday等成员。 - 进程时间:表示进程的 CPU 时间,包括用户态(user CPU time)和内核态(system CPU time),可通过
times()函数获取。 - 高精度时间:纳秒级时间,用
struct timespec(秒和纳秒)或struct timeval(秒和微秒)表示,适用于需要精确计时的场景,如多媒体处理或网络编程。
时间获取与转换
1 获取当前时间
-
time()函数:返回当前日历时间,示例代码如下:#include <time.h> #include <stdio.h> int main() { time_t current_time = time(NULL); printf("Current time: %ld\n", current_time); return 0; } -
gettimeofday()函数:获取高精度时间(微秒级),但已标记为过时,推荐使用clock_gettime()。
2 时间格式化与转换
-
localtime()和gmtime():将time_t转换为struct tm,前者返回本地时间,后者返回 UTC 时间。struct tm *local_tm = localtime(¤t_time); printf("Local time: %d-%d-%d %d:%d:%d\n", local_tm->tm_year + 1900, local_tm->tm_mon + 1, local_tm->tm_mday, local_tm->tm_hour, local_tm->tm_min, local_tm->tm_sec); -
strftime()函数:将struct tm格式化为字符串,支持自定义格式(如%Y-%m-%d %H:%M:%S)。
char buffer[80]; strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local_tm); printf("Formatted time: %s\n", buffer); -
mktime()函数:将struct tm转换回time_t,并自动处理无效日期(如 2 月 30 日)。
高精度时间编程
1 clock_gettime() 函数
clock_gettime() 是 POSIX 标准推荐的高精度时间获取函数,支持多种时钟源:
CLOCK_REALTIME:实时时间(受系统时间调整影响)。CLOCK_MONOTONIC:单调递增时间(不受系统时间调整影响,适合测量耗时)。CLOCK_PROCESS_CPUTIME_ID:当前进程的 CPU 时间。
示例代码:
#include <time.h>
#include <stdio.h>
int main() {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
printf("Monotonic time: %ld.%09ld seconds\n", ts.tv_sec, ts.tv_nsec);
return 0;
}
2 纳秒级休眠
nanosleep() 函数可实现纳秒级休眠,比 sleep() 更精确:
#include <time.h>
#include <stdio.h>
int main() {
struct timespec req = {1, 500000000}; // 1.5 秒
nanosleep(&req, NULL);
printf("Slept for 1.5 seconds\n");
return 0;
}
定时器与定时任务
1 软件定时器
Linux 提供了多种定时器机制:

alarm()函数:设置单次定时器,触发后发送SIGALRM信号。setitimer()函数:支持更灵活的定时器设置(如ITIMER_REAL、ITIMER_VIRTUAL)。
2 定时任务调度
crontab:用于周期性执行任务,如0 0 * * * /usr/bin/script.sh表示每天午夜运行脚本。at命令:用于一次性定时任务,如at 10:00 AM tomorrow表示明天上午 10 点执行任务。
时间同步与网络时间协议
在分布式系统中,时间同步至关重要,Linux 提供了以下工具:
- NTP(Network Time Protocol):通过
ntpd或chrony服务同步系统时间,确保多台服务器时间一致。 timedatectl命令:管理系统时间和时区,如timedatectl set-timezone "Asia/Shanghai"。
实践注意事项
- 时区处理:避免直接使用
tm_hour等字段,而是通过strftime()或localtime_r()(线程安全版本)处理时区。 - 时间精度:高精度场景下优先使用
clock_gettime(),避免gettimeofday()的精度限制。 - 线程安全:
localtime()是非线程安全的,应使用localtime_r()替代。 - 时间校准:在关键应用中,需考虑时钟漂移,定期通过 NTP 同步时间。
Linux 时间编程涵盖了从基础时间获取到高精度定时器的广泛功能,开发者需根据应用场景选择合适的时间表示方式和 API,并注意线程安全、时区处理和精度要求,通过灵活运用 time.h 中的函数和系统工具,可以高效实现时间相关的功能,为系统开发和运维提供可靠的时间支持。



















