我想在每毫秒計算一些數據的線程內運行一個循環。但我在睡眠功能方面遇到問題。它睡得太久了。每秒運行一次循環sleep_for
我創建在Visual Studio中基本控制檯應用程序:
#include <windows.h>
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
typedef std::chrono::high_resolution_clock Clock;
int _tmain(int argc, _TCHAR* argv[])
{
int iIdx = 0;
bool bRun = true;
auto aTimeStart = Clock::now();
while (bRun){
iIdx++;
if (iIdx >= 500) bRun = false;
//Sleep(1);
this_thread::sleep_for(chrono::microseconds(10));
}
printf("Duration: %i ms\n", chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - aTimeStart).count());
cin.get();
return 0;
}
此打印出:持續時間:5000毫秒 同樣的結果被打印,當我使用的Sleep(1);
我期望的持續時間爲500毫秒,而不是5000毫秒。我在這裏做錯了什麼?
更新:
我使用Visual Studio 2013年現在,我已經安裝了Visual Studio 2015年,它的精 - 打印出:持續時間:500毫秒(有時其527毫秒)。
但是,這sleep_for仍然不是很準確,所以我會尋找其他解決方案。
C++標準時鍾在很大程度上取決於操作系統的基本時鐘,也許Windows不有這樣一個高分辨率的時鐘? –
適用於我的機器™。你使用的是什麼版本的Visual Studio? VS2015之前'std :: chrono :: high_resolution_clock'沒有很好的分辨率。 Boost的替代品有很大的下降,你可以嘗試在Boost.Chrono中使用 – melak47
你也在while循環下執行操作,這將需要一定的循環次數。只是爲了檢查你是否修改iIdx ++到++ iIdx是否會在輸出中產生任何影響? – Invictus