编程之美 之 让CPU占用率听你指挥

来源:互联网 发布:淘宝如何设置单件包邮 编辑:程序博客网 时间:2024/06/11 17:03

昨天在bbs上淘到了这本编程之美,顺手刷了第一章,非常有意思。第一章的要求是要控制CPU曲线,绘制出相应的形状。
拿到这个问题,我的第一反应是, 是不是有这么一个API,能在任务管理器上的相应区域直接绘制图形呢? 然后就去查找API, 可惜搜索能力不行,终于还是没有找到。
然后看书上的解释, 太棒了。


解决这道题目的核心是, CPU占用率的概念,应该是指 CPU忙的时间与总时间的比,他是一个平均值的概念。也就是说,通过控制CPU忙闲时间的比值,我们可以大致控制CPU的占用率。


通过这个思想可以 控制CPU绘制各种我们想要的图形 >_<

方波
这里写图片描述
sin波
这里写图片描述
直线
这里写图片描述

源码如下:

// ==================【控制cpu曲线】=================// @ author         :       zhyh2010// @ date           :       20150609// @ version        :       1.0// @ description    :       核心: 在任务管理器的一个刷新周期内//                      CPU 忙的时间 和 刷新时间的比率就是 CPU 的占用率//                      CPU 显示的实际只是一个平均值// ================【end of 控制cpu曲线】===============#include <stdlib.h>#include <stdio.h>#include <windows.h>#include <math.h>// void busy1()// {//  for (int i = 0; i != 10; i++)//  {//      system("start calc");//  }//  system("taskkill /f /im calc.exe");//  printf("busy\n");// }void DrawSin(){    system("title sin");    const float PI = 3.1415926535;    const int count = 360;    const int GAP = 1;    const DWORD totalTime = 200;    float x = 0;    float ratio[count] = { 0 };    for (int i = 0; i != count; i++, x += GAP)        ratio[i] = 0.5 * sin(PI * x / 180.0);    for (int i = 0; TRUE; i = (i + 1) % count)    {        DWORD startTime = GetTickCount();        while (GetTickCount() - startTime < (0.5 + ratio[i]) * totalTime);        Sleep((0.5 - ratio[i]) * totalTime);    }}void DrawLinear(float ratio = 0.9){    system("title drawline");    const DWORD totalTime = 200;        while (true)    {        DWORD startTime = GetTickCount();        while (GetTickCount() - startTime < ratio * totalTime);        Sleep((1 - ratio) * totalTime);    }   }void DrawSquareWave(float max = 0.9, float min = 0.1){    system("title squareWave");    const DWORD totalTime = 200;    const int count = 300;    for (int i = 0; TRUE; i = (i + 1) % count)    {        float ratio = (i > count / 2) ? max : min;        DWORD startTime = GetTickCount();        while (GetTickCount() - startTime < ratio * totalTime);        Sleep((1 - ratio) * totalTime);    }}void main(){    // ===============【设置进程所在cpu】=================    SetProcessAffinityMask(GetCurrentProcess(), 1);    DrawLinear();    //DrawSin();    //DrawSquareWave();}

参考文章
编程之美:让CPU占用率曲线听你指挥

0 0
原创粉丝点击