(如果您的系统管理员更改了系统时间,或者时区的冬季时间和夏季时间不同,则这里缺少所有答案。因此...)
在Linux上使用:clock_gettime(CLOCK_MONOTONIC_RAW, &time_variable);
如果系统管理员更改时间,或者您所在的国家/地区的冬季时间不同于夏季时间,则不会受到影响。
#include <stdio.h>
#include <time.h>
#include <unistd.h> /* for sleep() */
int main() {
struct timespec begin, end;
clock_gettime(CLOCK_MONOTONIC_RAW, &begin);
sleep(1); // waste some time
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
printf ("Total time = %f seconds\n",
(end.tv_nsec - begin.tv_nsec) / 1000000000.0 +
(end.tv_sec - begin.tv_sec));
}
man clock_gettime
状态:
CLOCK_MONOTONIC
Clock that cannot be set and represents monotonic time since some unspecified starting point. This clock is not affected by discontinuous jumps in the system time
(e.g., if the system administrator manually changes the clock), but is affected by the incremental adjustments performed by adjtime(3) and NTP.