问题描述
我用c 编写了这个简短的程序,但是每当我运行它时,我的电脑风扇就开始快速旋转。我是在以错误的方式做某事,还是时间库只是以某种方式占用大量 CPU?代码如下:
#include <stdio.h>
#include <time.h>
void delay(int seconds){
int clocks_to_wait = seconds * CLOCKS_PER_SEC;
clock_t time = clock();
while(clock() < time + clocks_to_wait){
}
}
int main(){
while(1){
printf("\r");
printf("-");
delay(1);
printf("\r");
printf("\\");
delay(1);
printf("\r");
printf("|");
delay(1);
printf("\r");
printf("/");
delay(1);
printf("\r");
printf("-");
delay(1);
}
return 0;
}
我的猜测是空的 while 循环使处理器变热?我说得对吗?
编辑:问题已解决,来源:Simple <Time.h> program takes large amount CPU
解决方法
是的,像这样的空 while 循环只会占用 100% 的 CPU 时间,忙着等待直到时间赶上您想要等待的时间。
如果您想等待而不消耗 CPU 时间(并且浪费电池加热设备和运行风扇),您需要使用 OS 延迟,在不使用 CPU 的情况下等待。在 Posix(Linux、OSX、UNIX 等)系统上,这是 sleep
,它休眠指定秒数,或 nanosleep
调用,它休眠 timespec
,它指定以纳秒为单位的延迟。
在您的情况下,只需将 delay(1);
调用替换为 sleep(1);