写数据库作业,需要获取纳秒级别的时间,但一开始以为直接 chrono 或者 clock_gettime 就可以,但求出来但全部是微妙级别的时间,和纳秒差了 3 个数量级...
这玩意就,坑了我好久
解决方案如下 https://stackoverflow.com/questions/43451565/store-timestamps-in-nanoseconds-c
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif
inline long long now() {
timespec timestamp;
#ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
timestamp.tv_sec = mts.tv_sec;
timestamp.tv_nsec = mts.tv_nsec;
#else
clock_gettime(CLOCK_REALTIME, ×tamp);
#endif
return (long long)timestamp.tv_sec * 1000000000LL + timestamp.tv_nsec;
}
版权属于: Alan Clarke's Blog
原文地址: https://blog.xalanq.com/macos-cpp-get-nanoseconds/
转载时必须以链接形式注明原始出处及本声明。