读编程之美(一) 让cpu占用率听你指挥

实现对多核cpu的控制,一个画sin曲线,一个画直线。因为电脑的配置不同,可能结果不是很理想,调整程序中的时间参数就可以了。

#include <Windows.h>
#include <process.h>    //for 多线程
#include <math.h>
#include <iostream>
using namespace std;

void TimeSlice(int BusyTime, int IdleTime)
{
	int iStart = ::GetTickCount();
	while(::GetTickCount() - iStart < BusyTime);

	Sleep( IdleTime );
}

unsigned __stdcall DrawLine( LPVOID param )
{
	unsigned iDelay = reinterpret_cast<int>(param);
	double percentage = iDelay * 0.01;
	const int TotalTime = 30;
	int busyTime = static_cast<int>(TotalTime * percentage);
	int idleTime = TotalTime - busyTime;

	while (true)
	{
		TimeSlice( busyTime, idleTime );
	}

	return 0;
}

unsigned __stdcall DrawSin( LPVOID param )
{
	const double PI = 3.1415926;
	const int INTERVAL  = 200;
	const int COUNT = 100;
	const double SPLIT = 2.0 / COUNT;

	int half = static_cast<int>(INTERVAL * 0.5);
	int busySpan[COUNT];
	int idleSpan[COUNT];
	double radian = 0;
	for ( int i = 0; i < COUNT; i++ )
	{
		busySpan[i] = static_cast<int>(half + half * sin( radian * PI ));
		idleSpan[i] = INTERVAL - busySpan[i];
		radian += SPLIT;
	}

	int cnt = 0;
	while (true)
	{
		TimeSlice( busySpan[cnt], INTERVAL-busySpan[cnt] );
	
		cnt++;
		if (cnt == COUNT)
		{
			cnt = 0;
		}
	}

	return 0;
}

int main()
{
	SYSTEM_INFO info;
	GetSystemInfo(&info);
	cout << info.dwNumberOfProcessors << endl;
	cout << info.dwProcessorType << endl;

	unsigned param = 50;
	unsigned        tid;
	unsigned long thd1, thd2;

	for ( int i = 0; i < info.dwNumberOfProcessors; i++ )
	{
		unsigned long mark = 0x00000001 << i;
		if ( i % 2)
		{
			thd1 = _beginthreadex(NULL,
				0,
				DrawLine,
				(void *)param,
				0,
				&tid);
			SetThreadAffinityMask( (HANDLE)thd1, mark );
		}
		else
		{
			thd2 = _beginthreadex(NULL,
				0,
				DrawSin,
				NULL,
				0,
				&tid);
			SetThreadAffinityMask( (HANDLE)thd2, mark );
		}
	}

	Sleep(100000);

	if(thd1 != NULL)
	{
		CloseHandle((HANDLE)thd1);
	}

	if(thd2 != NULL)
	{
		CloseHandle((HANDLE)thd2);
	}
	
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值