【发布时间】:2016-06-14 23:27:33
【问题描述】:
让我们有以下代码,它只是测量std::this_thread::sleep_for 的持续时间,调用时间为 20 毫秒:
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
using namespace std::chrono;
int main()
{
for (int i = 0; i < 20; i++)
{
auto start = steady_clock::now();
this_thread::sleep_for(milliseconds(20));
auto end = steady_clock::now();
duration<double, milli> elapsed = end - start;
cout << "Waited " << elapsed.count() << " ms\n";
}
}
当使用工具集 v120(VS2013 的)编译运行时,我得到了预期的结果,即:
Waited 20.0026 ms
Waited 20.0025 ms
Waited 20.0025 ms
Waited 20.0026 ms
Waited 20.0025 ms
Waited 20.0025 ms
Waited 20.0026 ms
Waited 20.0025 ms
Waited 20.0025 ms
Waited 20.0026 ms
但是当使用 VS2015 的工具集 v140 运行时,结果有些令人惊讶,并且不尊重 msdn 和 cppreference.com sleep_for 描述的承诺(sleep_for 阻止当前线程的执行 至少指定的sleep_duration)。它们如下:
Waited 19.7793 ms
Waited 19.9415 ms
Waited 19.6056 ms
Waited 19.9687 ms
Waited 19.608 ms
Waited 19.589 ms
Waited 20.5435 ms
Waited 19.5669 ms
Waited 19.6802 ms
Waited 19.5381 ms
这怎么可能,我怎样才能让 VS2015 的 sleep_for 至少像预期的那样休眠?
问候,大卫
编辑:
根据要求,这些是我的设置和操作系统详细信息:
操作系统:
Windows 7 专业版 64 位
Visual Studios:2010 Ultimate、2013 Community、2015 Professional with Update 1
编译器设置:
Win32 控制台应用程序的默认设置,
任何调试和发布配置,
任何 x86 和 x64 目标平台架构
【问题讨论】:
-
我一般在循环中使用
sleep_until(),以防早起。我认为早醒不应该发生,但在 GCC Linux 上,至少,只要进程收到信号(显然不是你的问题),早醒似乎就会发生。 -
我在本地看不到相同的结果,例如在rextester.com/l/cpp_online_compiler_visual 上(它也在使用 VS2015)。考虑添加有关您的确切编译器设置、目标架构、主机操作系统、机器规格等的更多信息。
-
@Yirkha:我在描述中添加了更多关于我的条件的详细信息。至于你的结果 - 它看起来像是在我的系统中寻找微小的差异。
标签: c++ c++11 visual-studio-2013 visual-studio-2015