了解time_t调用

我编写了以下内容以将本地时间打印为字符串:

 char time_buffer[25];
 time_t t = time(&t);
 strftime(time_buffer, 25, "%c", localtime(&t));
 printf("Formatted time: %sn", time_buffer);

但是,代码对我来说没有太大意义(即使我已经编写了它)。关于它的几个问题:

  • 如何time_t t = time(&t)工作?这是设置本地时间的结构吗?它从哪里抢时间?
  • 是什么之间的区别time(&t)localtime(&t)?为什么两者都需要?

回答

time() is implemented in libc. For example, here is the implementation in glibc 2.33 for Linux:

time (time_t *t)
{
  return INLINE_VSYSCALL (time, 1, t);
}

which asks the kernel via a syscall for the time. The kernel, in turn, maintains a variable somewhere with this information. The kernel gets the time on boot from a battery backed clock and often subsequently sync'ed with a reference clock source (on Linux this would be via the Network Time Protocol (NTP)).

time()返回一个 time_t(在我的系统上是 long 的 typedef),它是自纪元以来的秒数(这是时间的度量,与时区无关)。 在您选择的任何时区(在 Linux 上通过环境变量 TZ)localtime()返回一个struct tm *具有日期和时间(秒、分钟、小时、日、月、年等)的常用组件。


以上是了解time_t调用的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>