码迷,mamicode.com
首页 > 系统相关 > 详细

linux 设置cpu占用率

时间:2020-11-26 14:19:38      阅读:10      评论:0      收藏:0      [点我收藏+]

标签:环境安装   create   spec   csdn   within   tick   name   ret   ons   

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

linux 设置cpu占用率

标签:环境安装   create   spec   csdn   within   tick   name   ret   ons   

原文地址:https://www.cnblogs.com/g2thend/p/14019705.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!