0
点赞
收藏
分享

微信扫一扫

linux控制cpu占用率

小黑Neo 2022-10-31 阅读 165


之前在<编程之美>上提到说控制cpu的使用率使能在任务管理器上画一条正弦线
现在下面提供一个在Linux平台上实现的控制cpu频率在某个值
​cpu_load.c​​

#include <iostream>
#include <pthread.h>
#include <time.h>
#include <math.h>
#include <unistd.h>

using namespace std;

typedef long long int int64;
const int NUM_THREADS = 1; //CPU core nums
int INTERVAL = 100;
int cpuinfo = 15; //CPU utilization rate

// time unit is "ms"
int64 GetTickCount()
{
timespec now;
int64 sec, nsec;

clock_gettime(CLOCK_MONOTONIC, &now);
sec = now.tv_sec;
nsec = now.tv_nsec;

return sec * 1000 + nsec / 1000000;
}

void* CPUCost(void *args)
{
int busyTime = INTERVAL * cpuinfo / 100;
int idleTime = INTERVAL - busyTime;
int64 startTime = 0;

std::cout << "XXXX CPUCost" << std::endl;
std::cout << "XXXX cpuinfo = " << cpuinfo << std::endl;

/*
* within INTERVAL ms, INTERVAL = busyTime + idleTime,
* spend busyTime ms to let cpu busy,
* spend idleTime ms top let cpu idle
*/
while (true) {
startTime = GetTickCount();
while((GetTickCount() - startTime) <= busyTime);
usleep(idleTime * 1000);
}
}

int main(int argc, char **argv)
{
pthread_t t[NUM_THREADS];
int ret;

std::cout << "please input cpu utilization rate" << std::endl;
std::cin >> cpuinfo;
for(int i = 0; i < NUM_THREADS; i++) {
ret = pthread_create(&t[i], NULL, CPUCost, NULL);
if(ret)
std::cout << "XXXX create err" << std::endl;
}

pthread_exit(NULL);
return 0;
}

编译: ​​g++ cpu_load.c -lpthread -lrt -o cpu_load​

1.设置cpu的占用率为10%

linux控制cpu占用率_编程之美


linux控制cpu占用率_ios_02

2.设置cpu的占用率为60%

linux控制cpu占用率_编程之美_03


linux控制cpu占用率_编程之美_04

3.设置cpu的占用率为100%

linux控制cpu占用率_编程之美_05


linux控制cpu占用率_ios_06


程序需要在空闲的机器上运行,才能比较精确地获取到设置的CPU利用率


举报

相关推荐

0 条评论