《编程之美--微软技术面试心得》笔记-固定CPU占用率

写一个程序,让用户来决定任务管理器(Task Manager)的CPU占用率,程序越精简越好,编程语言不限。

#include<iostream>
#include<Windows.h>
using namespace std;
int main()
{
    for (;;)
    {
        for (int i = 0; i < 960000; i++)
            ;
        Sleep(10);
    }
    return 0;
}

以上程序对于不同的CPU,很难确定n取值。对于某一台指定的计算机,可能CPU的占用率刚好为50%。实际情况中不同电脑CPU不同,并且不同电脑上运行的程序也不同,如何保持50%的CPU占用率?
下面是大牛的程序:

#include<iostream>
#include<Windows.h>
#include<stdlib.h>
#include<math.h>

const double SPLIT = 0.01;
const int COUNT = 200;
const double PI = 3.14159265;
const int INTERVAL = 300;
using namespace std;
int main()
{
    DWORD busySpan[COUNT];
    DWORD idleSpan[COUNT];
    int half = INTERVAL / 2;
    double radian = 0.0;
    for (int i = 0; i < COUNT; i++)
    {
        busySpan[i] = (DWORD)(half + (sin(PI * radian)*half));
        idleSpan[i] = INTERVAL - busySpan[i];
        radian += SPLIT;
    }

    DWORD startTime = 0;
    int j = 0;
    while (true)
    {
        j = j % COUNT;
        startTime = GetTickCount();//caculate the time since the system started
        while ((GetTickCount() - startTime) <= busySpan[j])
            ;
        Sleep(idleSpan[j]);
        j++;
    }
    return 0;
}

    原文作者:超超级钢铁侠
    原文地址: https://blog.csdn.net/qq_23851075/article/details/51993498
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞