2023年7月3日发(作者:)
Linux控制CPU使⽤率曾经看过《编程之美》上提到说使 CPU的使⽤率固定在百分之多少。然后这次刚好要⽤到这个东西,下⾯是⼀个简单的实现。基于多线程:Linux 版本: 1 #include
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 = _sec;18 int64 nsec = _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++ -lpthread -lrt -o testCPU 注:因为只是⽤来测试,所以写的很粗糙。⼤致的原理是对的,细节部分请⼤家⾃⾏优化了。
Windows 版本: 1 #include
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 }注: 没有实现多线程。
发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1688329448a121119.html
评论列表(0条)