在C中获取当前时间/日期/日的最有效方法

har*_*ari 4 c freebsd systemtime processing-efficiency

用C语言获取当前时间/日期/日/年的最有效方法是什么?由于我必须多次执行,我需要一种真正有效的方法.我在freeBSD上.

提前致谢.

Ale*_*tte 6

/* ctime example */
#include <stdio.h>
#include <time.h>

int main ()
{
  time_t rawtime;

  time ( &rawtime );
  printf ( "The current local time is: %s", ctime (&rawtime) );

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果需要ctime,可以使用ctime.


caf*_*caf 5

标准C只提供一种获取时间的方法 - time()可以用localtime()或转换为时间/日期/年份gmtime().如此简单,这必须是最有效的方式.

任何其他方法都是特定于操作系统的,您还没有告诉我们您正在使用的操作系统.

  • 如果你担心`gmtime`或`localtime`很慢,你可以简单地调用它们一次,然后根据从'time`获得的以秒为单位的delta值调整结果.就POSIX而言,这是可移植的,但不是普通的C,因为普通的C没有指定`time_t`类型的格式,除了它是算术类型. (2认同)