多cpu(多核)下让cpu占用率成正弦曲线

基本思路是新建一线程,让这个线程只在某一cpu上运行。这个线程的作用是控制单个cpu的占用率。

 

#include <Windows.h>
#include <stdlib.h>
#include <math.h>


const double SPLIT = 0.01;
const int COUNT = 200;
const double PI = 3.1415926;
const int INTERVAL = 300;


static DWORD WINAPI myProc(LPVOID p)
{
 DWORD busySpan[COUNT];
 DWORD idleSpan[COUNT];

 int half = INTERVAL / 2;
 double radian = 0.0;

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

 DWORD startTime = 0;
 int j=0;
 while (true)
 {
  j=j%COUNT;
  startTime = GetTickCount();
  while ( (GetTickCount() - startTime) <= busySpan[j])
  {
   ;
  }
  Sleep(idleSpan[j]);
  j++;
 }
}


int _tmain(int argc, _TCHAR* argv[])
{
 char szbuf[200];
 DWORD id;
 HANDLE h = CreateThread(NULL, 0, myProc, &szbuf, CREATE_SUSPENDED, &id);
 if (NULL == h)
 {
  printf("error /n");
  return 0;
 }

 SetThreadAffinityMask(h, 1);

 ResumeThread(h);

 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0)
 {
  CloseHandle(h);
  printf("error /n");
  return 0 ;
 }

 CloseHandle(h);

 

 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞天红猪侠001

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值