Loading

linux 设置cpu占用率

1,环境安装

##
#编译环境
yum groupinstall -y "Development Tools"


##cat cpu_load
#以下为代码

#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  set cores 
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

2,使用
使用finalshell 可以看到总体的cpu 大小然后根据核心的个数凑成指定的占用率
这个程序的运行时占用一个核心, 可以修改代码,设置核心数为cpu 具体数

./cpu_load
60

来源:https://blog.csdn.net/luckywang1103/article/details/79202751

posted @ 2020-11-22 16:09  Lust4Life  阅读(841)  评论(0编辑  收藏  举报