我正在尝试用 C(适用于 Windows)做一个秒表,代码似乎可以工作,但 sleep 功能的时间与实时不匹配。
进程返回 0 (0x0) 执行时间:1.907 秒 按任意键继续。
问题是执行时间大约是 2 秒,但应该只有 1 秒。只是想知道我做错了什么,因为 Windows 中的 sleep 功能接受毫秒作为参数,它应该可以工作。这是代码
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
int milliseconds=0;
int seconds=0;
int counter;
for(counter=0;counter<1000;counter++) {
Sleep(1);
milliseconds = milliseconds + 1;
printf("%d\n",milliseconds);
if(milliseconds==1000) {
seconds = seconds + 1;
milliseconds = 0;
printf("seconds: %d",seconds);
}
}
return 0;
}
最佳答案
您正在休眠,超时为 1 毫秒。实际上,您正在放弃当前线程的时间片,默认情况下为 15.6 毫秒。但是如果你有一个像 Visual Studio 一样运行的 WPF 应用程序,它将被设置为 1ms。 sleep 不会早于您想 sleep 的时间返回,因此您可以有效地等待时间片,这些时间片加起来为 2 秒的 sleep 时间。 如果你使用像 ETWController 这样的分析器可以看到线程直接在等待。
您会看到我们有 1004 个上下文切换事件,它们平均等待 1.6 毫秒,而不是您预期的 1 毫秒。操作系统调度程序如何影响您的 sleep 时间还有很多。最好的办法是测量。参见示例 SpinWait is dangerous .
当我例如关闭所有强制执行 1ms 系统计时器的应用程序我会得到 6.5 秒的 sleep 时间! 为了检查真正的等待时间,我使用了带有高分辨率计时器的代码来打印真正的等待时间:
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <chrono>
int main()
{
int milliseconds = 0;
int seconds = 0;
int counter;
auto start = std::chrono::high_resolution_clock::now();
for (counter = 0; counter<1000; counter++) {
Sleep(1);
milliseconds = milliseconds + 1;
//printf("%d\n", milliseconds);
if (milliseconds == 1000) {
seconds = seconds + 1;
milliseconds = 0;
printf("\nseconds: %d", seconds);
}
}
auto stop = std::chrono::high_resolution_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start).count();
printf("Duration: %dms", ms);
return 0;
}
这是输出:
ClockRes v2.0 - View the system clock resolution
Copyright (C) 2009 Mark Russinovich
SysInternals - www.sysinternals.com
Maximum timer interval: 15.625 ms
Minimum timer interval: 0.500 ms
Current timer interval: 1.000 ms
seconds: 1
Duration: 1713ms
ClockRes v2.0 - View the system clock resolution
Copyright (C) 2009 Mark Russinovich
SysInternals - www.sysinternals.com
Maximum timer interval: 15.625 ms
Minimum timer interval: 0.500 ms
Current timer interval: 15.625 ms
seconds: 1
Duration: 6593ms
关于c - CodeBlocks(适用于 Windows)中的 sleep C 功能无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37510664/