在《编程之美》上有这么一道题,题目是:编程让CPU的占用率呈正弦曲线变化。 初看这题基本没什么思路,后来了解到CPU占用率的计算公式就找到突破口了。
CPU占用率计算公式:
CPU占用率 = 运行时间/总时间 x 100%
有了上面的公式,只需要让一个时间片内运行的时间占该时间片的比例呈正弦变化即可。
//正弦曲线的
double time = 0.0 ;
double runtime ;
int c;
while(1)
{
runtime = 100 + 100 * sin(time);
time += 0.05 ;
c = clock();
while(clock() - c < runtime );
Sleep(200 - runtime );
}
//横线的
while(1)
{
int start = clock();
while(clock() - start < 10 );
Sleep(10);
}
//单向斜线的
int k = -1;
int c = 0;
int runtime ;
while(1)
{
runtime = 100 + k * ( c++ % 101 ) ;
int start = clock();
while(clock() - start < runtime );
Sleep(100 - runtime );
}
//双向斜线的
int k = 1 ;
int c = 0;
int runtime ;
while(1)
{
runtime = (int)(c<100) * ( 100 + -1 * ( c % 100 )) + (int)(c>100) * (c-100);
c = c++ % 200 ;
int start = clock();
while(clock() - start < runtime);
Sleep(100 - runtime );
}
正弦曲线的效果
单向斜线的效果
双向斜线的效果