Linux 控制CPU使用率


曾經看過《編程之美》上提到說使 CPU的使用率固定在百分之多少。然后這次剛好要用到這個東西,下面是一個簡單的實現。基於多線程:

Linux 版本:

 1 #include <iostream>
 2 #include <pthread.h>
 3 #include <time.h>
 4 #include <math.h>
 5 
 6 using namespace std;
 7 
 8 typedef long long int int64;
 9 const int NUM_THREADS = 24; // CPU 核數
10 int eachTime = 100;
11 int cpuinfo = 0; // 占用率
12 
13 int64 GetTickCount()
14 {
15     timespec now;
16     clock_gettime(CLOCK_MONOTONIC, &now);
17     int64 sec = now.tv_sec;
18     int64 nsec = now.tv_nsec;
19     return sec*1000 + nsec/1000000;
20 }
21 
22 
23 void* CPUCost(void *args)
24 {
25     std::cout << "XXXX CPUCost" << std::endl;
26     int busyTime = eachTime * cpuinfo / 100;
27     //std::cout << "XXXX cpuinfo = " << cpuinfo << std::endl;
28     int idleTime = eachTime - busyTime;
29     int64 startTime = 0;
30     while (true)
31     {
32         startTime = GetTickCount();
33         while((GetTickCount() - startTime) <= busyTime)
34         {
35             ;
36         }
37 
38         usleep(100);
39     }
40 }
41 
42 
43 
44 int main(int argc, char **argv)
45 {
46     std::cin >> cpuinfo;
47     pthread_t t[NUM_THREADS];
48     for(int i = 0; i < NUM_THREADS; i++)
49     {
50         int ret = pthread_create(&t[i], NULL, CPUCost, NULL);
51         if(ret)
52          {
53              std::cout << "XXXX create err" << std::endl;
54          }
55     }
56 
57     pthread_exit(NULL);
58 
59 
60     return 0;
61 }

編譯方式: g++ testCPU.cc -lpthread -lrt -o testCPU

    注:因為只是用來測試,所以寫的很粗糙。大致的原理是對的,細節部分請大家自行優化了。

 

Windows 版本:

 1 #include<iostream>
 2 #include<Windows.h>
 3 #include<cmath>
 4 
 5 using namespace std;
 6 
 7 int eachTime = 100;
 8 void CPU(int busy,int idle);
 9 
10 int main()
11 {    
12     int level;    
13     cin >> level;    
14     int busyTime = eachTime*level / 100;    
15     int idleTime = eachTime - busyTime;    
16     CPU(busyTime,idleTime);    
17     return 0;
18 }
19 void CPU(int busy, int idle)
20 {    
21     INT64 startTime = 0;    
22     while (true)
23     {        
24         startTime = GetTickCount();
25         while ((GetTickCount()-startTime)<=busy)        
26         {            
27             ;        
28         }        
29         Sleep(idle);    
30     }
31 }

注: 沒有實現多線程。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM