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

时间:2016-11-21 20:26:04

标签: c++ ns-3

由于网络模拟器-3工具不支持chrono,我需要在不使用chrono的情况下使用C ++进行编码,以便以纳秒为单位获得时间戳。

1 个答案:

答案 0 :(得分:1)

在Ubuntu 64上,我使用POSIX

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);
}

用法:

uint64_t startNS = MNS::getSystemNanosecond()

//... do stuff that takes time

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