代码改变世界

双核cpu使用率画正弦曲线

2009-07-02 22:20  Iron  阅读(637)  评论(0编辑  收藏  举报
 1 //c++代码
 2 
 3 #include <windows.h>
 4 #include <stdlib.h>
 5 #include <iostream>
 6 #include <math.h>
 7 #include <tchar.h>
 8 
 9 const double SPLIT = 0.01;
10 const int COUNT = 200;
11 const double PI = 3.14159265;
12 const int INTERVAL = 300;
13 
14 int main(int argc,char* argv[])
15 {
16  SYSTEM_INFO systemInfo;
17  ::GetSystemInfo(&systemInfo);
18 
19  std::cout << systemInfo.wProcessorArchitecture << std::endl;
20  std::cout << systemInfo.dwProcessorType << std::endl;
21  std::cout << "处理器数目:" << systemInfo.dwNumberOfProcessors << std::endl;
22  std::cout << "处理器掩码:" << systemInfo.dwActiveProcessorMask << std::endl;
23 
24  //PDWORD_PTR process1,process2;
25  //GetProcessAffinityMask(::GetCurrentProcess(),process1,process2);
26  std::cout << SetProcessAffinityMask(::GetCurrentProcess(),0x00000001) << std::endl;
27  
28  //if(!SetThreadAffinityMask(::GetCurrentProcess(),0x00000003))
29  {
30   //std::cout << "错误:" << GetLastError() << std::endl;
31   //::MessageBox(GetActiveWindow(),_T("asdf"),_T("asdf"),MB_OK);
32  }
33 
34  //绘制正弦曲线 
35  DWORD busySpan[COUNT];
36  DWORD idleSpan[COUNT];
37  int half = INTERVAL/2;
38  double radian = 0.0;
39  for(int i=0;i<COUNT;i++)
40  {
41   busySpan[i] = (DWORD)(half + (sin(PI*radian)*half));
42   idleSpan[i] = INTERVAL - busySpan[i];
43   radian += SPLIT;  
44  }
45  DWORD startTime  = 0;
46  int j = 0;
47  while(true)
48  {
49   j=j%COUNT;
50   startTime = GetTickCount();
51   while((GetTickCount()-startTime)<=busySpan[j])
52   ;
53   Sleep(idleSpan[j]);
54   j++;
55  }
56  return 0;
57 }

 

结果

代码来自《编程之美》