编程之美读书笔记之控制CPU使用率

最近再一次拜读大作<编程之美>

mark之后,学习一下

其中一篇,提到了如何控制Cpu使用率.

题目:写一个程序,让用户来决定Windows任务管理器(Task Manager)的CPU占用率。程序越精简越好,计算机语言不限。例如,可以实现下面三种情况:

1.    CPU的占用率固定在50%,为一条直线

2.    CPU的占用率为一条直线,但是具体占用率由命令行参数决定(参数范围1~ 100)

3.    CPU的占用率状态是一个正弦曲线

#include "stdafx.h"
#include <windows.h>
#include <math.h>
#include <stdio.h>

const double SPLIT = 0.01;//间隔COUNT * SPLIT = 2 2PI刚好一个周期
const int COUNT = 200;//采样次数
const double PI = 3.1415926535898; 
const int INTERVAL = 300;//周期为60s = 200ms * 300ms

DWORD WINAPI DrawSinLine(LPVOID parm)
{
	DWORD busySpan[COUNT];
	DWORD idleSpan[COUNT];
	int half = INTERVAL / 2;
	double raido = 0.0;
	printf("Draw Sin Line\n");
	for (int i = 0; i < COUNT; i++)
	{
		busySpan[i] = DWORD(half + (sin(PI * raido) * half));
		idleSpan[i] = INTERVAL - busySpan[i];
		raido += SPLIT; 
	}
	DWORD starttime;
	int j = 0;
	while (TRUE)
	{
		j = j % COUNT;
		starttime = GetTickCount();
		while((GetTickCount() - starttime) <= busySpan[j]);
		Sleep(idleSpan[j]);
		j++;
	}
	return 0;
}

DWORD WINAPI DrawLine(LPVOID parm)
{
	DWORD usage = *(LPDWORD)parm;
	unsigned int busytime = 20;
	unsigned int idletime = (100 * busytime / usage) - busytime;
	DWORD starttime;
	printf("Draw Line\n");
	while (TRUE)
	{
		starttime = GetTickCount();
		while((GetTickCount() - starttime) <= busytime);
		Sleep(idletime);
	}
	return 0;
}

int main(int argc, char* argv[])
{
	SYSTEM_INFO sysinfo;
	GetSystemInfo(&sysinfo);
	HANDLE hthread;
	DWORD usage = atoi(argv[1]);
	hthread = (HANDLE)CreateThread(NULL,  
		0,  
		DrawLine,  
		&usage,  
		0,  
		NULL);  
	SetThreadAffinityMask(hthread, sysinfo.dwNumberOfProcessors - 1);
	CloseHandle(hthread);
	hthread = (HANDLE)CreateThread(NULL,  
		0,  
		DrawSinLine,  
		NULL,  
		0,  
		NULL); 
	SetThreadAffinityMask(hthread, sysinfo.dwNumberOfProcessors);
	WaitForSingleObject(hthread, INFINITE);
	CloseHandle(hthread);
	return 0;
}

这里笔者的本机环境是双核CPU,所以创建了两个线程,并且设置线程喜好让两个线程分别跑在不同的CPU上,一个画直线.一个画正弦曲线.

画出来的效果还算勉强近似吧.


编程之美读书笔记之控制CPU使用率_第1张图片


你可能感兴趣的:(编程,windows,manager,null,读书,winapi)