tscns
tscns copied to clipboard
精度不高的一个简单解决方案
思路是利用线程缓存
int64_t steady_time_now()
{
using namespace std::chrono;
static thread_local int64_t tsc = 0;
static thread_local int64_t now = 0;
int64_t new_tsc = __builtin_ia32_rdtsc();
if (new_tsc - tsc > 1000 * 1000) // according to the precision
{
tsc = new_tsc;
now = duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
}
return now;
}
这就不是纳秒精度的了,只有毫秒精度
这就不是纳秒精度的了,只有毫秒精度
是的,适用频繁调用,但是精度要求不高的情况。通常日志记录,定时器之类的, 毫秒精度基本够用。 主要是这个方案使用简单,不需要校准,也不需要担心时间跳变之类的问题。
如果只是毫秒精度下面这个足够快
int64_t rdns() {
timespec ts;
::clock_gettime(CLOCK_MONOTONIC_COARSE, &ts);
return ts.tv_sec * 1000'000'000 + ts.tv_nsec;
}