【发布时间】:2016-09-27 09:33:14
【问题描述】:
我正在尝试用 C 语言(适用于 Windows)做一个秒表,代码似乎可以工作,但睡眠功能的时间与实时不匹配。
进程返回 0 (0x0) 执行时间:1.907 秒 按任意键继续。
问题是执行时间大约是 2 秒,但应该只有 1 秒。只是想知道我做错了什么,因为 Windows 中的睡眠功能接受毫秒作为它应该工作的参数。这是代码
#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;
}
【问题讨论】:
-
你得到哪个输出?
-
输出为:998 999 1000 秒:1 进程返回 0 (0x0) 执行时间:1.898 s 按任意键继续。
-
您在测量时遇到了一个常见错误:您将单个测量值相加。每个都会带来一个可能很小的特定错误。但是,将单个结果相加也会增加错误。尝试在这里测量绝对值。
-
每个循环休眠一毫秒,然后也做它的事情,所以每次迭代是 1ms 加上“做事情的时间”。完成这 1000 次最终需要 1000 毫秒 plus 1000 * “做事的时间”。
-
这个“
printf("%d\n",milliseconds);”实际上打印的是计数迭代,而不是毫秒。
标签: c windows codeblocks sleep