C标准库 - <time.h> 学习笔记
介绍
<time.h>
是 C 标准库中的一个头文件,其中包含了一些关于时间处理的函数和类型。
<time.h>
定义了一些结构体和函数,用于在程序中处理日期和时间、计算时间差等功能。这些结构体包括 struct tm
和 struct timespec
,函数包括 asctime
、clock
、ctime
、difftime
、gmtime
、localtime
等等。
常用函数
clock()
clock()
函数返回程序执行起(一般为程序开头),处理器时间所使用的时钟数。
cCopy Code#include <stdio.h>
#include <time.h>
int main() {
clock_t start = clock(); // 获取起始时间戳
// do something ...
clock_t end = clock(); // 获取结束时间戳
double time_cost = (double) (end - start) / CLOCKS_PER_SEC;
printf("Time cost: %f seconds\n", time_cost);
return 0;
}
time()
time()
函数返回自 1970 年 1 月 1 日起到当前时间的秒数。
cCopy Code#include <stdio.h>
#include <time.h>
int main() {
time_t t = time(NULL);
printf("Seconds since January 1, 1970: %ld", t);
return 0;
}
localtime()
localtime()
函数将一个表示时间的秒数转换为本地时间,并以 struct tm
结构体的形式返回。
cCopy Code#include <stdio.h>
#include <time.h>
int main() {
time_t t = time(NULL);
struct tm *now = localtime(&t);
printf("Current local time: %02d:%02d:%02d\n", now->tm_hour, now->tm_min, now->tm_sec);
return 0;
}
strftime()
strftime()
函数可以将时间格式化为指定的格式。
cCopy Code#include <stdio.h>
#include <time.h>
int main() {
time_t t = time(NULL);
struct tm *now = localtime(&t);
char buffer[80];
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", now);
printf("Formatted time string: %s\n", buffer);
return 0;
}
结论
<time.h>
头文件中定义的函数可以方便地获取和处理时间。我们可以使用这些函数进行时间戳的计算、本地时间的转换,以及时间格式的输出等等。