Linux 测量时间问题! std::chrono, QueryPerformanceCounter, clock_ge

Linux measuring time problem! std::chrono, QueryPerformanceCounter, clock_gettime

本文关键字:QueryPerformanceCounter clock ge 测量 chrono 问题 std Linux 时间      更新时间:2023-10-16

我在Linux中使用clock_gettime((和Windows中的QueryPerformanceCounter((来测量时间。在测量时间时,我遇到了一个有趣的案例。

首先,我正在无限循环中计算 DeltaTime。此循环调用一些更新函数。为了计算 DeltaTime,程序在更新函数中等待 40 毫秒,因为更新函数尚空。

然后,在编译为Win64-Debug的程序中,我测量DeltaTime。它大约是 0.040f。只要程序正在运行,这种情况就会继续(Win64-Release 也像这样工作(。它运行正常。

但是在编译为 Linux64-Debug 或 Linux64-Release 的程序中,存在一个问题。

当程序开始运行时。一切都很正常。增量时间约为 0.040f。但过了一会儿,deltatime 被计算为 0.12XXf 或 0.132XX,紧随其后的是 0.040f。等等。

我以为我正确地使用了QueryPerformanceCounter,而错误地使用了clock_gettime((。然后我决定用标准库std::chrono::high_resolution_clock尝试一下,但它是一样的。没有变化。

#define MICROSECONDS (1000*1000)
auto prev_time = std::chrono::high_resolution_clock::now();
decltype(prev_time) current_time;
while(1)
{
current_time = std::chrono::high_resolution_clock::now();
int64_t deltaTime = std::chrono::duration_cast<std::chrono::microseconds>(current_time - previous_time).count();
printf("DeltaTime: %f", deltaTime/(float)MICROSECONDS);
NetworkManager::instance().Update();
prev_time = current_time;
}

void NetworkManager::Update()
{
auto start = std::chrono::high_resolution_clock::now();
decltype(start) end;
while(1)
{
end = std::chrono::high_resolution_clock::now();
int64_t y = std::chrono::duration_cast<std::chrono::microseconds>(end-start).count();
if(y/(float)MICROSECONDS >= 0.040f)
break;
}
return;
}

正常

问题

可能的原因:

  1. 您的clock_gettime未使用 VDSO,而是系统调用 - 如果在strace下运行,将在 下可见,可以在现代内核版本上配置。
  2. 您的线程被抢占(被调度程序从 CPU 中取出(。若要运行干净试验,请以实时优先级运行应用,并将其固定到特定的 CPU 内核。

另外,我会在实验时禁用 CPU 频率缩放。

相关文章:
  • 没有找到相关文章