我刚刚写了一个简单的代码,以hh:mm:ss格式显示时间。该代码是从性能角度看有什么不对?
#include <stdio.h>
#include <time.h>
int main()
{
time_t curtime;
int h, m, s, ps;
struct tm *x = localtime(&curtime);
time(&curtime);
ps = (*x).tm_sec;
while(1)
{
time(&curtime);
x = localtime(&curtime);
h = (*x).tm_hour;
m = (*x).tm_min;
s = (*x).tm_sec;
if(s != ps)
{
ps = s;
printf("%02d:%02d:%02d\n", h, m, s);
}
}
return(0);
}
代码编译并运行正常。然而,CPU使用率似乎非常高。当我使用'top'查看CPU使用率时,它显示cpu%为96-100%(我可以听到电脑风扇大声)。如何从性能角度改进代码,使代码简单而简洁?
请参阅[是否可以问代码优化问题帮助?](http://meta.stackoverflow.com/a/286559/1079354)以查看您缺少的内容。现在,没有什么我能看到的,会导致不良表现(除了那美妙的无限循环)。 – Makoto
你正在退出'while(1)'? – Gopi
虽然不是我所关注的。好吧,我可以添加一些条件说“如果(PS == 50)休息”。这会使它成为更好的代码吗?这不是我正在谈论的while循环。 CPU使用率仍然很高。 – anupamb