uptime命令

2020-11-28  本文已影响0人  小怪兽狂殴奥特曼

网上很多博文解释uptime命令都是错误的。uptime是用来查看cpu负载的情况
uptime的输出主要看load average,有三个值,分别表示cpu在1分钟,5分钟,15分钟内的系统负载。
那么怎么看呢?
首先必须要看系统的cpu核心数,可以用lscpu看 CPU(s)一栏得到。
假设为4核心,uptime输出load average: 5.12,2.00,1.00
那么应该解释为:
1分钟负载(5.12-4)/4=28%,单核平均过载28%
5分钟负载(2-4)/4=-50%,单核平均空闲50%
5分钟负载(1-4)/4=-75%,单核平均空闲75%

可以用如下代码解释

#include <iostream>
#include<stdio.h>
#include<unistd.h>
#include <pthread.h>

const int TIME_UINT_US=1;
const int TIME_UINT_MS=1000*TIME_UINT_US;
const int TIME_UNIT_SEC=1000000UL;
const int SAMPLE_INTVL=100*TIME_UINT_MS;
const int SAMPLE_CNT=1000;

int get_cpu_num()
{
    int cpu_num = sysconf(_SC_NPROCESSORS_CONF);
    printf("_SC_NPROCESSORS_CONF=%d\n",cpu_num);
    return cpu_num;
}

u_long GetTickCount()
{
    timespec now;
    clock_gettime(CLOCK_MONOTONIC, &now);
    u_long sec = now.tv_sec;
    u_long nsec = now.tv_nsec;
    return sec*TIME_UNIT_SEC + nsec/1000;
}
void cpu_cost(int rate)
{
    int busy_time=SAMPLE_INTVL*rate/100;
    int idle_time=SAMPLE_INTVL*(100-rate)/100;
    while(true)
    {
        u_long start_time=GetTickCount();
        while(GetTickCount()-start_time < busy_time);
        usleep(idle_time);
    }
}

// 系统负载
int g_rate=50;


void *task(void * arg)
{
    cpu_cost(g_rate);
}
int main() {


    for(int i=0;i<get_cpu_num()-1;i++)
    {
        pthread_t pid;
        pthread_create(&pid,NULL,task,NULL);
    }
    cpu_cost(g_rate);
    return 0;
}

双核机器上,设定负载g_rate=50,最终update出来的值在1.00左右。

上一篇 下一篇

猜你喜欢

热点阅读