控制CPU占用率曲线

编程之美的第一个问题,我的机器是双核的,用文中的代码,得到的曲线波动比较大额,受其他进程的影响比较大。文中提到10ms接近windows的调度时间片,如果选得太小,会造成线程被频繁唤醒和挂起,造成内核不稳定。

#include "windows.h"

#include "stdlib.h"

#include "math.h"



// 时间片的尺度大概是 10 ms

void control_cpu_percentage(int per) {

    DWORD sleep_time = 30;    //ms

    DWORD busy_time = per * sleep_time / (100 - per);

    DWORD start = GetTickCount();



    while (true) {

        while (GetTickCount() - start <= busy_time);

        Sleep(sleep_time);

        start = GetTickCount();

    }

}



int main() {

    SetThreadAffinityMask(GetCurrentThread(), 0); 

    control_cpu_percentage(30);

    //while(1);

}

 

你可能感兴趣的:(cpu)