如何在C+中以纳秒为单位获取当前时间戳+;不使用chrono? 由于在网络仿真器-3工具中不支持计时,所以我需要在C++中使用代码来实现时间戳,以毫微秒的时间戳记。 uint64_t MNS::getSystemNanosecond(voi

如何在C+中以纳秒为单位获取当前时间戳+;不使用chrono? 由于在网络仿真器-3工具中不支持计时,所以我需要在C++中使用代码来实现时间戳,以毫微秒的时间戳记。 uint64_t MNS::getSystemNanosecond(voi,c++,ns-3,C++,Ns 3,如何在C+中以纳秒为单位获取当前时间戳+;不使用chrono? 由于在网络仿真器-3工具中不支持计时,所以我需要在C++中使用代码来实现时间戳,以毫微秒的时间戳记。 uint64_t MNS::getSystemNanosecond(void) { const uint64_t NSPS = 1000000000; //struct timespec { __time_t tv_sec; long int tv_nsec; }; -- total 8 b

如何在C+中以纳秒为单位获取当前时间戳+;不使用chrono?

由于在网络仿真器-3工具中不支持计时,所以我需要在C++中使用代码来实现时间戳,以毫微秒的时间戳记。

uint64_t MNS::getSystemNanosecond(void)
{
   const uint64_t NSPS = 1000000000;

   //struct timespec {  __time_t tv_sec;    long int tv_nsec;  };  -- total 8 bytes
   struct timespec ts;

   // CLOCK_REALTIME - system wide real time clock
   int status = clock_gettime(CLOCK_REALTIME, &ts);
   dtbAssert(0 == status);

   // to 8 byte     from   4 byte
   uint64_t uli_nsec = static_cast<uint64_t>(ts.tv_nsec);
   uint64_t uli_sec  = static_cast<uint64_t>(ts.tv_sec);

   uint64_t total_ns = uli_nsec + (uli_sec * NSPS);

   return(total_ns);
}

没有目标操作系统无法回答的问题。无论操作系统如何,要想在微秒以下获得好的时间确实很难;如果你不能;调整你的处境直到你可以。计时,我需要得到秒的小数部分。我正在寻找一种方法来做这件事。有人能推荐一下吗!纳秒很难获得,因为许多处理器在10到100纳秒的时间内执行指令。从记忆中读取时间是个问题。毫秒或微秒就足够了吗?需要纳秒吗?你真的需要精确到1E-9秒吗?在大多数情况下,1E-3毫秒就足够了。某些应用可能需要1E-6或微秒。在我以前的桌面上,POSIXAPI“clock_gettime(clock_REALTIME,&ts)”的持续时间约为1600 ns。
uint64_t startNS = MNS::getSystemNanosecond()

//... do stuff that takes time

uint64_t durationNS = MNS::getSystemNanosecond() - startNS;