我在centos 7服务器中调用此函数。

我发现std::this_thread::sleep_for(chrono::nanoseconds(1))实际上睡了一毫秒,请问有什么解释吗?我认为可能是操作系统设置引起的吗?

最佳答案

您已经在其他答案中涵盖了所问的问题,但是在注释中还提出了一个问题:



不用调用sleep_for,而产生线程的执行槽,您可以忙于 sleep 。也就是说,循环直到经过一定的时间。它通常会以使该CPU线程无法执行其他任何操作为代价获得更准确的结果。

这是一个名为busy_sleep()的函数的示例:

// get a rough estimate of how much overhead there is in calling buzy_sleep()
std::chrono::nanoseconds calc_overhead() {
    using namespace std::chrono;
    constexpr size_t tests = 1001;
    constexpr auto timer = 200us;

    auto init = [&timer]() {
        auto end = steady_clock::now() + timer;
        while(steady_clock::now() < end);
    };

    time_point<steady_clock> start;
    nanoseconds dur[tests];

    for(auto& d : dur) {
        start = steady_clock::now();
        init();
        d = steady_clock::now() - start - timer;
    }
    std::sort(std::begin(dur), std::end(dur));
    // get the median value or something a little less as in this example:
    return dur[tests / 3];
}

// initialize the overhead constant that will be used in busy_sleep()
static const std::chrono::nanoseconds overhead = calc_overhead();

inline void busy_sleep(std::chrono::nanoseconds t) {
    auto end = std::chrono::steady_clock::now() + t - overhead;
    while(std::chrono::steady_clock::now() < end);
}

Demo

注意:这是在接受之后更新的,因为我注意到开销计算有时可能会变得非常错误。更新后的示例应该不那么脆弱。

10-06 11:19