簡體   English   中英

C++ 休眠功能

[英]C++ Sleep functions

我正在嘗試執行一個有點准確的睡眠 function。 我測量了我的睡眠 function 睡了多長時間並將它們並排放置。 下面示例的格式是:“預期毫秒:結果毫秒”。

我嘗試了很多選擇,但仍然找不到解決方案。 以下是我嘗試的路線:

路線 1

Sleep(<time>)
/* milliseconds */
38.4344 46.4354
41.728 47.7818
0.556 0.0012
43.6532 46.8087
0.4523 0.0009
62.8664 76.995
1.5363 15.4592
75.9435 78.1663
91.5194 92.0786
0.6533 0.001
39.7423 45.6729
0.5022 0.0008
54.7837 60.597
0.4248 0.0011
39.2165 45.6977
0.4854 0.0008
10.6741 15.054
  • 幾乎沒有明顯的 CPU 使用率,這很好,但結果仍然不准確。

路線 2

/* Windows sleep in 100ns units */
BOOLEAN nanosleep(LONGLONG ns){
    /* Declarations */
    HANDLE timer;   /* Timer handle */
    LARGE_INTEGER li;   /* Time defintion */
    /* Create timer */
    if(!(timer = CreateWaitableTimer(NULL, TRUE, NULL)))
        return FALSE;
    /* Set timer properties */
    li.QuadPart = -ns;
    if(!SetWaitableTimer(timer, &li, 0, NULL, NULL, FALSE)){
        CloseHandle(timer);
        return FALSE;
    }
    /* Start & wait for timer */
    WaitForSingleObject(timer, INFINITE);
    /* Clean resources */
    CloseHandle(timer);
    /* Slept without problems */
    return TRUE;
}
/* milliseconds */
1.057 14.7561
66.5977 79.4437
0.409 14.7597
152.053 156.757
1.26725 15.747
19.025 30.6343
67.3235 78.678
0.4203 14.4713
65.3507 74.4703
0.4525 14.8102
28.6145 29.7099
72.0035 74.7315
0.5971 14.8625
55.7059 59.3889
0.4791 14.5419
50.9913 61.6719
0.5929 15.5558
  • CPU 使用率低,這很好,但仍然不准確。
  • 我在某處讀到使用多媒體定時器可以提供准確的睡眠。

代碼源

路線 3

void super_sleep(double ms)
{
    auto a = std::chrono::steady_clock::now();
    while ((std::chrono::steady_clock::now() - a) < std::chrono::milliseconds(static_cast<int>(ms))) {
        continue;
    }
}
/* milliseconds */
55.7059 55.0006
0.5669 0.0008
66.5977 66.0009
0.4213 0.0009
0.7228 0.0007
7.5374 7.0006
0.8825 0.0007
0.4143 0.0009
59.8062 59.0005
51.7157 51.0006
54.0807 54.0006
11.8834 11.0006
65.3507 65.0004
14.429 14.0006
0.4452 0.0012
1.6797 1.0004
96.0012 96.0006
  • 效果比其他嘗試好很多,但占用了我高達 7% 的 CPU。

我還嘗試使用std::this_thread::sleep_for()並收到與 Route 2 類似的結果。

我在 Windows 10 20H2、C++17 和 i9 9900k 上。

獲得相當好的准確度的一種方法(但不是完美的,因為 Windows 不是實時操作系統)是使用標准睡眠功能之一,但睡眠時間很短 - 然后忙於等待剩余時間。 這通常會使 CPU 使用率保持在較低水平。

template<class T, class U>
void Sleep(std::chrono::duration<T,U> ss) {
    auto target = std::chrono::steady_clock::now() + ss; // the target end time

    // Sleep short. 5 ms is just an example. You need to trim that parameter.
    std::this_thread::sleep_until(target - std::chrono::milliseconds(5));

    // busy-wait the remaining time
    while(std::chrono::steady_clock::now() < target) {}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM