在 Linux 下,gettimeofday
函數(shù)用于獲取當(dāng)前系統(tǒng)時(shí)間,以秒和微秒為單位
#include <sys/time.h>
gettimeofday
函數(shù)獲取當(dāng)前時(shí)間:struct timeval currentTime;
gettimeofday(¤tTime, NULL);
currentTime
結(jié)構(gòu)體將包含兩個(gè)成員:tv_sec
(秒)和 tv_usec
(微秒)。
根據(jù)需要處理 tv_sec
和 tv_usec
。例如,將時(shí)間值轉(zhuǎn)換為字符串:
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 系統(tǒng)上廣泛使用,但在其他類(lèi) Unix 系統(tǒng)(如 macOS 和 FreeBSD)上可能有所不同。因此,在跨平臺(tái)編程時(shí)要注意兼容性問(wèn)題。