曾经看过《编程之美》上提到说使 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 }
注: 没有实现多线程。