C time.h标准库

C语言<time.h>标准库详解

C语言 标准库

时间处理函数的完整指南 – 以通俗易懂的方式讲解时间处理原理和函数使用

当前系统时间 (使用time.h函数获取)
加载中…
⏱️

概述

time.h 是C语言中处理日期和时间的标准库头文件。它包含了获取系统时间、转换时间格式、计算时间差等函数。

核心作用: 处理时间相关的操作,包括获取当前时间、时间格式转换和时间计算。

时间在计算机中通常表示为整数,记录从某个固定时间点(称为”纪元”)开始经过的秒数。

大白话解释: 想象计算机内部有一个巨大的秒表,从1970年1月1日午夜开始计时。time.h 提供的方法可以读取这个秒表的值,还能把秒数转换成我们能理解的年月日时分秒格式。
📊

核心数据类型

time.h 定义了三种重要的数据类型:

  • time_t 通常是一个整数类型,表示从”纪元”(1970年1月1日00:00 UTC)开始经过的秒数
  • clock_t 表示程序执行时间的类型,通常用于测量代码段的执行时间
  • struct tm 一个结构体,包含日历时间的各个组成部分:
struct tm {
  int tm_sec; // 秒 [0-59]
  int tm_min; // 分 [0-59]
  int tm_hour; // 时 [0-23]
  int tm_mday; // 月份中的日 [1-31]
  int tm_mon; // 月份 [0-11](0代表一月)
  int tm_year; // 自1900年起的年数
  int tm_wday; // 星期几 [0-6](0代表周日)
  int tm_yday; // 一年中的第几天 [0-365]
  int tm_isdst; // 夏令时标志(正数表示启用,0表示未启用,负数表示未知)
};
注意: tm_year 表示的是自1900年起的年数。例如,2023年对应的tm_year值为123(2023-1900=123)。
🕒

时间获取函数

这些函数用于获取当前时间:

  • time() 获取当前日历时间(纪元开始的秒数)
  • clock() 返回程序执行开始以来使用的处理器时间
// 使用time()获取当前时间
time_t now;
time(&now); // 将当前时间存入now变量

// 使用clock()测量程序运行时间
clock_t start = clock();
// … 执行一些代码 …
clock_t end = clock();
double cpu_time = ((double) (end – start)) / CLOCKS_PER_SEC;
CLOCKS_PER_SEC: 一个宏定义,表示每秒钟的时钟周期数。用于将clock()的返回值转换为秒。
🔄

时间转换函数

这些函数用于不同时间格式之间的转换:

  • localtime() 将time_t转换为本地时间(struct tm)
  • gmtime() 将time_t转换为UTC时间(struct tm)
  • mktime() 将本地时间(struct tm)转换为time_t
  • asctime() 将struct tm转换为字符串(固定格式)
  • ctime() 将time_t转换为本地时间的字符串形式
  • strftime() 自定义格式输出时间字符串
// 将time_t转换为可读格式
time_t now = time(NULL);
struct tm *local = localtime(&now);
printf(“当前时间: %s”, asctime(local));

// 使用strftime自定义格式
char buffer[80];
strftime(buffer, 80, “%Y年%m月%d日 %H:%M:%S”, local);
printf(“格式化时间: %s”, buffer);

时间差计算

计算两个时间点之间的差异:

  • difftime() 计算两个time_t值之间的差异(以秒为单位)
time_t start_time, end_time;
time(&start_time); // 记录开始时间

// … 执行一些耗时操作 …

time(&end_time); // 记录结束时间
double diff = difftime(end_time, start_time);
printf(“操作耗时: %.2f 秒\n”, diff);
注意: 虽然可以直接用减法计算time_t时间差,但使用difftime()是更可移植的方法,因为time_t可能不是整型。

对于更精确的时间差测量(毫秒级):

clock_t start = clock();
// … 要测量的代码 …
clock_t end = clock();
double elapsed = (double)(end – start) / CLOCKS_PER_SEC * 1000;
printf(“代码执行时间: %.2f 毫秒\n”, elapsed);
💡

实用技巧与注意事项

  • 时区处理 localtime()会考虑本地时区,而gmtime()返回UTC时间
  • 夏令时 struct tm中的tm_isdst字段会指示是否处于夏令时
  • 线程安全 localtime(), gmtime()等函数返回指向静态内存的指针,非线程安全
  • 时间精度 time()通常精确到秒,clock()精确到毫秒级
  • 格式化符号 strftime()的常用格式符号:
    %Y-年,%m-月,%d-日,%H-时(24),%M-分,%S-秒,%A-星期名称
线程安全版本: 在一些实现中,提供了如localtime_r(), gmtime_r()等线程安全版本函数。
// 安全的时间转换(跨平台)
time_t now = time(NULL);
struct tm result;
localtime_r(&now, &result); // 使用线程安全版本

// 或者
struct tm *safe_local = localtime(&now);
struct tm my_tm = *safe_local; // 复制数据

© 2023 C语言标准库学习指南 | 时间处理函数详解

编程小白也能理解的时间处理知识 | 实际编程中多练习这些函数的使用

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部