Linux 控制CPU使用率

时间:2022-07-07 05:59:14

曾经看过《编程之美》上提到说使 CPU的使用率固定在百分之多少。然后这次刚好要用到这个东西,下面是一个简单的实现。基于多线程:

Linux 版本:

 #include <iostream>
#include <pthread.h>
#include <time.h>
#include <math.h> using namespace std; typedef long long int int64;
const int NUM_THREADS = ; // CPU 核数
int eachTime = ;
int cpuinfo = ; // 占用率 int64 GetTickCount()
{
timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
int64 sec = now.tv_sec;
int64 nsec = now.tv_nsec;
return sec* + nsec/;
} void* CPUCost(void *args)
{
std::cout << "XXXX CPUCost" << std::endl;
int busyTime = eachTime * cpuinfo / ;
//std::cout << "XXXX cpuinfo = " << cpuinfo << std::endl;
int idleTime = eachTime - busyTime;
int64 startTime = ;
while (true)
{
startTime = GetTickCount();
while((GetTickCount() - startTime) <= busyTime)
{
;
} usleep();
}
} int main(int argc, char **argv)
{
std::cin >> cpuinfo;
pthread_t t[NUM_THREADS];
for(int i = ; i < NUM_THREADS; i++)
{
int ret = pthread_create(&t[i], NULL, CPUCost, NULL);
if(ret)
{
std::cout << "XXXX create err" << std::endl;
}
} pthread_exit(NULL); return ;
}

编译方式: g++ testCPU.cc -lpthread -lrt -o testCPU

注:因为只是用来测试,所以写的很粗糙。大致的原理是对的,细节部分请大家自行优化了。

Windows 版本:

 #include<iostream>
#include<Windows.h>
#include<cmath> using namespace std; int eachTime = ;
void CPU(int busy,int idle); int main()
{
int level;
cin >> level;
int busyTime = eachTime*level / ;
int idleTime = eachTime - busyTime;
CPU(busyTime,idleTime);
return ;
}
void CPU(int busy, int idle)
{
INT64 startTime = ;
while (true)
{
startTime = GetTickCount();
while ((GetTickCount()-startTime)<=busy)
{
;
}
Sleep(idle);
}
}

注: 没有实现多线程。