linux之cpu模拟负载程序

12 篇文章 0 订阅
4 篇文章 0 订阅

工作中我们经常会遇到这样的问题,需要模拟cpu的负载程序,例如模拟cpu占有率抬升10%、20%、50%、70%等,那这样的程序应该如何实现呢?它的原理是什么样的呢?

思想

创建一个应用程序,该应用程序的作用可以根据用户的设置占用指定的cpu占有率。例如用户指定占用10%,则该应用程序占用cpu占有率为10%;若设置cpu占有率为50%,则应用程序程序的cpu占有率为50%。

占用固定cpu占有率的程序

#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 = 8; //CPU core nums
int INTERVAL = 100;
int cpuinfo = 70; //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;
        std::cout<<"pthread_create i= "<<i<<std::endl;
    }

    pthread_exit(NULL);
    return 0;
}

上文代码中NUM_THREADS变量的含义是cpu有几个核,该变量修改为cpu的核数;INTERVAL值默认为100,无需修改;cpuinfo,全局变量,用于保存应用程序占用的cpu占有率;GetTickCount函数的作用是获取毫秒时间;CPUCost函数是线程函数,核心逻辑:

    /*
     * within INTERVAL ms, INTERVAL = busyTime + idleTime,
     * spend busyTime ms to let cpu busy,
     * spend idleTime ms top let cpu idle
     */
    while (true) 
    {
        startTime = GetTickCount();  //获取一个开始时间,单位为ms
        //busyTime和idleTime的总和为100ms,即在100ms的时间间隔内,程序运行时间为//busyTime,程序空闲时间为idleTime,通过这样的方式来控制cpu占用率,如下的是循环是控制程序运行busyTime时间
        while((GetTickCount() - startTime) <= busyTime);
//usleep控制程序睡眠idleTime时间,让出cpu
        usleep(idleTime * 1000);
    }

注意事项:

由于我的环境cpu有8个核,若指定cpu占有率的为70%,则每个核的cpu占有率为70%,总的cpu占有率为70%,所有的cpu核占有率综合为560%左右(70%*8)。

运行结果如下所示:

可以看到cpu各个核的cpu占有率均在70%以上,综合的cpu占有率也是79%,各个核的cpu占有率总计为520.9基本与预期相符,达到预期目的。

cpu占有率动态变化程序(按照正弦函数规律控制cpu占有率)

代码如下所示:

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

using namespace std;

#define PI acos(-1)
#define DISCRETEVALUE 100
typedef long long int int64;
const int NUM_THREADS = 8; //CPU core nums
int INTERVAL = 100;
int cpuinfo = 70; //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;
    int busyTime = 50;
    int idleTime = 50;
    int64 startTime = 0;
    //每次递增间隔
    float value = 2*PI/DISCRETEVALUE;
    int index = 0;

    cout<<"value = "<<value <<" PI = "<<sin(PI)<<endl;
    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);
        //添加正弦曲线,
        if(index > DISCRETEVALUE)
            index = 0;
        busyTime = 50 + sin(index*value)*50;
        idleTime = 100 - busyTime;
        cout<<"busyTime = "<<busyTime<<"  idleTime = "<<idleTime << "index*value = "<< index*value<<"  sin(index*value)*50 = "<<sin(index*value)*50<<endl;
        index++;
    }
}

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;
        std::cout<<"pthread_create i= "<<i<<std::endl;
    }

    pthread_exit(NULL);
    return 0;
}

结果显示

 完美实现cpu占有率动态控制。

总结

核心思想是在100ms内动态的分配应用程序运行时间和空闲时间的比例,从而实现达到控制cpu占有率的目的。

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Linux中,可以使用stress命令来模拟系统负载较高的场景。通过模拟各种高负载情况,我们可以更好地理解系统的瓶颈,并掌握性能检测工具的使用方法。 stress命令的基本用法如下: ``` stress [选项 [参数] ``` 其中,选项可以用于指定stress命令的行为,参数用于指定要模拟的高负载场景。 举个例子,如果我们想要模拟CPU负载较高的情况,可以使用下面的命令: ``` stress --cpu 4 --timeout 60s ``` 上述命令中,`--cpu 4`表示使用4个CPU核心进行负载,`--timeout 60s`表示持续模拟60秒的高负载。 除了模拟CPU负载,stress命令还可以模拟内存、I/O、线程等不同类型的负载。例如,如果我们想要模拟内存负载较高的情况,可以使用下面的命令: ``` stress --vm 2 --vm-bytes 1G --timeout 60s ``` 上述命令中,`--vm 2`表示使用2个虚拟机来进行内存负载,`--vm-bytes 1G`表示每个虚拟机使用1GB的内存,`--timeout 60s`表示持续模拟60秒的高负载。 使用stress命令可以帮助我们在测试环境中模拟不同类型的高负载场景,以便更好地了解系统的性能瓶颈和优化策略。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [linux stress 命令 模拟系统高负载](https://blog.csdn.net/whatday/article/details/104477160)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [Linux系统常用的负载命令](https://blog.csdn.net/acccco/article/details/125727210)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值