在 Linux 下,gettimeofday 函数用于获取当前系统时间,以秒和微秒为单位
#include <sys/time.h>
gettimeofday 函数获取当前时间:struct timeval currentTime;
gettimeofday(¤tTime, NULL);
currentTime 结构体将包含两个成员:tv_sec(秒)和 tv_usec(微秒)。
根据需要处理 tv_sec 和 tv_usec。例如,将时间值转换为字符串:
char timeStr[26];
strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", ¤tTime);
或者将秒和微秒分别处理:
long seconds = currentTime.tv_sec;
long microseconds = currentTime.tv_usec;
timespec_get 或 clock_gettime。注意:gettimeofday 在 Linux 系统上广泛使用,但在其他类 Unix 系统(如 macOS 和 FreeBSD)上可能有所不同。因此,在跨平台编程时要注意兼容性问题。