c++ - 损坏的计时器或其他东西

标签 c++ c

我有一些必须帮助我的程序,但我无法处理时间。
聘请是一个代码:

#include <iostream>
using namespace std;
#include <time.h>
#include <Windows.h>

double diffclock(clock_t clock1) {
    clock_t clock2 = clock();
    double diffticks = clock1 - clock2;
    double diffms = diffticks / (CLOCKS_PER_SEC / 1000);

    return diffms;
}


int main()
{
    int wait = 134;
    clock_t fullbetween = clock();

    for (int i = 0; i < 5; i++) {
        Sleep(wait / 5);
        cout << wait / 5 << "  ";
    }
    cout << endl << "finish in " << diffclock(fullbetween) << " ms" << endl;
    return 0;
}

C++ 版本。同样的结果:

#include <iostream>
#include <chrono>
#include <ctime>
#include <thread>
#include <Windows.h>


int main()
{
    int wait = 134;
    auto start = std::chrono::system_clock::now();

    for (int i = 0; i < 5; i++) {
        std::this_thread::sleep_for(std::chrono::milliseconds(wait/5));
    }
    auto end = std::chrono::system_clock::now();

    auto int_ms = std::chrono::duration_cast<std::chrono::milliseconds> (end - start);

    std::cout << std::endl << "finish in " << int_ms.count() << " ms" << std::endl;
    return 0;
}

134/5 = 26 可以。但在最后一个“cout”中,它表明所有迭代大约需要 170 毫秒,而不是预期的 130 毫秒。为什么会这样?

对不起我的英语。

最佳答案

休眠函数的文档位于 https://learn.microsoft.com/en-gb/windows/win32/api/synchapi/nf-synchapi-sleep

Suspends the execution of the current thread until the time-out interval elapses.

The system clock "ticks" at a constant rate. If dwMilliseconds is less than the resolution of the system clock, the thread may sleep for less than the specified length of time. If dwMilliseconds is greater than one tick but less than two, the wait can be anywhere between one and two ticks, and so on.

Windows 系统上的刻度通常为 15.6 毫秒(每秒 64 个刻度),因此 26 变为 31.2。 这是挂起的线程可能再次激活的时间,不能保证它会立即开始执行。所以你的五次 sleep 变成了 156ms 加上一点开销。

文档继续介绍针对此行为的缓解措施,以及缓解措施将影响系统电源使用等的警告。

To increase the accuracy of the sleep interval, call the timeGetDevCaps function to determine the supported minimum timer resolution and the timeBeginPeriod function to set the timer resolution to its minimum.

关于c++ - 损坏的计时器或其他东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58959131/

相关文章:

c++ - 在 ofstream 中使用 sstream in 提供输出文件的名称

c++ - Blade 的扭曲效果 (glRotatef) 不起作用

c - 结构初始化性能

c - 良好的风格实践 : C variables

c - 释放在简单链表中分配的内存 - C

c - 为什么控件不进入repeat()函数?

c++ - 对不同版本的代码进行基准测试的选项有哪些(以避免膨胀和性能下降)?

c++ - libjpeg 解码为 BGR

c++ - 从文件中读取数据到C++中的多个数组

c++ - 在排序和旋转的数组中搜索