编程之美 之 让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
- 编程之美 之 让CPU占用率听你指挥
- 编程之美 - 让CPU占用率曲线听你指挥
- 编程之美:让CPU占用率曲线听你指挥
- 编程之美:让CPU占用率曲线听你指挥
- 编程之美:让CPU占用率曲线听你指挥
- 编程之美:让CPU占用率曲线听你指挥
- 编程之美:让CPU占用率曲线听你指挥
- 编程之美:让CPU占用率曲线听你指挥
- 编程之美:让CPU占用率曲线听你指挥
- 编程之美:让CPU占用率曲线听你指挥
- 编程之美读书笔记-让CPU占用率听你指挥
- 《编程之美》-- 让CPU占用率听你指挥
- 编程之美:让CPU占用率曲线听你指挥
- 读书笔记之编程之美 - 1.1 让CPU占用率曲线听你指挥
- 编程之美1.1让CPU占用率曲线听你指挥之解法一细节
- 《编程之美》之读书笔记 1.1让CPU占用率曲线听你指挥
- 《编程之美》“让CPU占用率听你指挥”学习笔记
- 编程之美读书笔记_1.1_让CPU占用率曲线听你指挥
- MYSQL使用group by时,查询结果的总记录数
- 80后的互联网北漂:你的未来在哪?
- 用java写的C语言词法分析
- 挑战面试编程:大整数的加、减、乘、除
- Android 编程下通过 Theme 和 Style 避免 APP 启动闪黑屏
- 编程之美 之 让CPU占用率听你指挥
- jsp页面的ajax取值
- Android 避免APP启动闪黑屏(Theme和Style)
- 前端菜鸟的成长学习之路(一)
- YGM欧版磨粉机微粉磨生产线
- 数据持久化(一)-----归档 读写 文件路径
- PB如何连接mysql数据库
- GRE阅读理解的主题
- UITableViewCell长按显示快捷菜单