Linux系统Load Average解析

简介: 很多小伙伴在遇到某一接口服务性能问题时,比如说,TPS上不去、响应时间拉长、应用系统出现卡顿,某一请求出现超时等等现象,往往显得苍白无力,无从下手。 针对系统负载性能,很大一部分人潜意识会认为CPU使用率等同系统负载,或者直接反应系统负载情况,这种理解对吗?本文将从2个纬度合理进行分析系统负载以及CPU与Load Average之间的关联。

      很多小伙伴在遇到某一接口服务性能问题时,比如说,TPS上不去、响应时间拉长、应用系统出现卡顿,某一请求出现超时等等现象,往往显得苍白无力,无从下手。

      针对系统负载性能,很大一部分人潜意识会认为CPU使用率等同系统负载,或者直接反应系统负载情况,这种理解对吗?本文将从2个纬度合理进行分析系统负载以及CPU与Load Average之间的关联。

      我们先看个场景:


[administrator@JavaLangOutOfMemory luga ]% uptime
9:25  up 2 days, 19:45, 2 users, load averages: 3.58 5.08 4.86
[administrator@JavaLangOutOfMemory luga ]% top
top - 09:26:42 up  4:12,  2 user, Load Avg: 3.58, 5.08, 4.86
[administrator@JavaLangOutOfMemory luga ]%cat /proc/loadavg 
3.58, 5.08, 4.86 42/3411 43603

     上述命令行执行后的输出结果,基本含义:最近1min、5min、15min的系统平均负载值;其包含State状态为R 和 D的两种Jobs,其他State状态不包含在内。

      其本质含义呢?主要释放以下信息:

    (1)如果平均值为 0.0,意味着系统处于空闲状态

   (2)如果 1min 平均值持续> 5min 或 15min 平均值,则表明负载正在增加

   (3)如果 1min 平均值持续< 5min 或 15min 平均值,则表明负载正在减少

   (4)如果值> 系统 CPU 的数量,系统可能存在性能问题

      关于R、D状态,简要描述如下:

      - R :  nr_running   表示正在运行,或者处于运行队列,可以被调度运行系统中正常运行的进程。

      若此状态导致的load高,系统就会特别卡。更准确的来说,R状态的多少,取决于CPU核数,若当前R状态大于主机CPU核数2倍以上,系统就会出现严重问题,出现多个R状态线程争抢CPU资源的情况。

      - D :  nr_uninterruptible  表示的是一个等待硬件资源睡眠且无法被中断的进程,出现该状态的进程一般是因为在等待IO,例如磁盘IO、网络IO等。这种状态是不可中断的,无论是kill,kill -9,还是kill -15等操作 。

      若此状态导致的load高,但是整个操作系统依然能够提供正常服务。

      具体,可参考部分源码loadavg.c:


// SPDX-License-Identifier: GPL-2.0
/*
 * kernel/sched/loadavg.c
 *
 * This file contains the magic bits required to compute the global loadavg
 * figure. Its a silly number but people think its important. We go through
 * great pains to make it work on big machines and tickless kernels.
 */
#include "sched.h"
/*
 * Global load-average calculations
 *
 * We take a distributed and async approach to calculating the global load-avg
 * in order to minimize overhead.
 *
 * The global load average is an exponentially decaying average of nr_running +
 * nr_uninterruptible.
 *
 * Once every LOAD_FREQ:
 *
 *   nr_active = 0;
 *   for_each_possible_cpu(cpu)
 *     nr_active += cpu_of(cpu)->nr_running + cpu_of(cpu)->nr_uninterruptible;
 *
 *   avenrun[n] = avenrun[0] * exp_n + nr_active * (1 - exp_n)
 *
 * Due to a number of reasons the above turns in the mess below:
 *
 *  - for_each_possible_cpu() is prohibitively expensive on machines with
 *    serious number of CPUs, therefore we need to take a distributed approach
 *    to calculating nr_active.
 *
 *        \Sum_i x_i(t) = \Sum_i x_i(t) - x_i(t_0) | x_i(t_0) := 0
 *                      = \Sum_i { \Sum_j=1 x_i(t_j) - x_i(t_j-1) }
 *
 *    So assuming nr_active := 0 when we start out -- true per definition, we
 *    can simply take per-CPU deltas and fold those into a global accumulate
 *    to obtain the same result. See calc_load_fold_active().
 *
 *    Furthermore, in order to avoid synchronizing all per-CPU delta folding
 *    across the machine, we assume 10 ticks is sufficient time for every
 *    CPU to have completed this task.
 *
 *    This places an upper-bound on the IRQ-off latency of the machine. Then
 *    again, being late doesn't loose the delta, just wrecks the sample.
 *
 *  - cpu_rq()->nr_uninterruptible isn't accurately tracked per-CPU because
 *    this would add another cross-CPU cacheline miss and atomic operation
 *    to the wakeup path. Instead we increment on whatever CPU the task ran
 *    when it went into uninterruptible state and decrement on whatever CPU
 *    did the wakeup. This means that only the sum of nr_uninterruptible over
 *    all CPUs yields the correct result.
 *
 *  This covers the NO_HZ=n code, for extra head-aches, see the comment below.
 */
/* Variables and functions for calc_load */
atomic_long_t calc_load_tasks;
unsigned long calc_load_update;
unsigned long avenrun[3];
EXPORT_SYMBOL(avenrun); /* should be removed */
/**
 * get_avenrun - get the load average array
 * @loads:     pointer to dest load array
 * @offset:    offset to add
 * @shift:     shift count to shift the result left
 *
 * These values are estimates at best, so no need for locking.
 */
void get_avenrun(unsigned long *loads, unsigned long offset, int shift)
{
       loads[0] = (avenrun[0] + offset) << shift;
       loads[1] = (avenrun[1] + offset) << shift;
       loads[2] = (avenrun[2] + offset) << shift;
}
long calc_load_fold_active(struct rq *this_rq, long adjust)
{
       long nr_active, delta = 0;
       nr_active = this_rq->nr_running - adjust;
       nr_active += (long)this_rq->nr_uninterruptible;
       if (nr_active != this_rq->calc_load_active) {
              delta = nr_active - this_rq->calc_load_active;
              this_rq->calc_load_active = nr_active;
       }
       return delta;
}
/**
 * fixed_power_int - compute: x^n, in O(log n) time
 *
 * @x:         base of the power
 * @frac_bits: fractional bits of @x
 * @n:         power to raise @x to.
 *
 * By exploiting the relation between the definition of the natural power
 * function: x^n := x*x*...*x (x multiplied by itself for n times), and
 * the binary encoding of numbers used by computers: n := \Sum n_i * 2^i,
 * (where: n_i \elem {0, 1}, the binary vector representing n),
 * we find: x^n := x^(\Sum n_i * 2^i) := \Prod x^(n_i * 2^i), which is
 * of course trivially computable in O(log_2 n), the length of our binary
 * vector.
 */
static unsigned long
fixed_power_int(unsigned long x, unsigned int frac_bits, unsigned int n)
{
       unsigned long result = 1UL << frac_bits;
       if (n) {
              for (;;) {
                     if (n & 1) {
                            result *= x;
                            result += 1UL << (frac_bits - 1);
                            result >>= frac_bits;
                     }
                     n >>= 1;
                     if (!n)
                            break;
                     x *= x;
                     x += 1UL << (frac_bits - 1);
                     x >>= frac_bits;
              }
       }
       return result;
}
/*
 * a1 = a0 * e + a * (1 - e)
 *
 * a2 = a1 * e + a * (1 - e)
 *    = (a0 * e + a * (1 - e)) * e + a * (1 - e)
 *    = a0 * e^2 + a * (1 - e) * (1 + e)
 *
 * a3 = a2 * e + a * (1 - e)
 *    = (a0 * e^2 + a * (1 - e) * (1 + e)) * e + a * (1 - e)
 *    = a0 * e^3 + a * (1 - e) * (1 + e + e^2)
 *
 *  ...
 *
 * an = a0 * e^n + a * (1 - e) * (1 + e + ... + e^n-1) [1]
 *    = a0 * e^n + a * (1 - e) * (1 - e^n)/(1 - e)
 *    = a0 * e^n + a * (1 - e^n)
 *
 * [1] application of the geometric series:
 *
 *              n         1 - x^(n+1)
 *     S_n := \Sum x^i = -------------
 *             i=0          1 - x
 */
unsigned long
calc_load_n(unsigned long load, unsigned long exp,
           unsigned long active, unsigned int n)
{
       return calc_load(load, fixed_power_int(exp, FSHIFT, n), active);
}
#ifdef CONFIG_NO_HZ_COMMON
/*
 * Handle NO_HZ for the global load-average.
 *
 * Since the above described distributed algorithm to compute the global
 * load-average relies on per-CPU sampling from the tick, it is affected by
 * NO_HZ.
 *
 * The basic idea is to fold the nr_active delta into a global NO_HZ-delta upon
 * entering NO_HZ state such that we can include this as an 'extra' CPU delta
 * when we read the global state.
 *
 * Obviously reality has to ruin such a delightfully simple scheme:
 *
 *  - When we go NO_HZ idle during the window, we can negate our sample
 *    contribution, causing under-accounting.
 *
 *    We avoid this by keeping two NO_HZ-delta counters and flipping them
 *    when the window starts, thus separating old and new NO_HZ load.
 *
 *    The only trick is the slight shift in index flip for read vs write.
 *
 *        0s            5s            10s           15s
 *          +10           +10           +10           +10
 *        |-|-----------|-|-----------|-|-----------|-|
 *    r:0 0 1           1 0           0 1           1 0
 *    w:0 1 1           0 0           1 1           0 0
 *
 *    This ensures we'll fold the old NO_HZ contribution in this window while
 *    accumlating the new one.
 *
 *  - When we wake up from NO_HZ during the window, we push up our
 *    contribution, since we effectively move our sample point to a known
 *    busy state.
 *
 *    This is solved by pushing the window forward, and thus skipping the
 *    sample, for this CPU (effectively using the NO_HZ-delta for this CPU which
 *    was in effect at the time the window opened). This also solves the issue
 *    of having to deal with a CPU having been in NO_HZ for multiple LOAD_FREQ
 *    intervals.
 *
 * When making the ILB scale, we should try to pull this in as well.
 */
static atomic_long_t calc_load_nohz[2];
static int calc_load_idx;
static inline int calc_load_write_idx(void)
{
       int idx = calc_load_idx;
       /*
        * See calc_global_nohz(), if we observe the new index, we also
        * need to observe the new update time.
        */
       smp_rmb();
       /*
        * If the folding window started, make sure we start writing in the
        * next NO_HZ-delta.
        */
       if (!time_before(jiffies, READ_ONCE(calc_load_update)))
              idx++;
       return idx & 1;
}
static inline int calc_load_read_idx(void)
{
       return calc_load_idx & 1;
}
static void calc_load_nohz_fold(struct rq *rq)
{
       long delta;
       delta = calc_load_fold_active(rq, 0);
       if (delta) {
              int idx = calc_load_write_idx();
              atomic_long_add(delta, &calc_load_nohz[idx]);
       }
}
void calc_load_nohz_start(void)
{
       /*
        * We're going into NO_HZ mode, if there's any pending delta, fold it
        * into the pending NO_HZ delta.
        */
       calc_load_nohz_fold(this_rq());
}
/*
 * Keep track of the load for NOHZ_FULL, must be called between
 * calc_load_nohz_{start,stop}().
 */
void calc_load_nohz_remote(struct rq *rq)
{
       calc_load_nohz_fold(rq);
}
void calc_load_nohz_stop(void)
{
       struct rq *this_rq = this_rq();
       /*
        * If we're still before the pending sample window, we're done.
        */
       this_rq->calc_load_update = READ_ONCE(calc_load_update);
       if (time_before(jiffies, this_rq->calc_load_update))
              return;
       /*
        * We woke inside or after the sample window, this means we're already
        * accounted through the nohz accounting, so skip the entire deal and
        * sync up for the next window.
        */
       if (time_before(jiffies, this_rq->calc_load_update + 10))
              this_rq->calc_load_update += LOAD_FREQ;
}
static long calc_load_nohz_read(void)
{
       int idx = calc_load_read_idx();
       long delta = 0;
       if (atomic_long_read(&calc_load_nohz[idx]))
              delta = atomic_long_xchg(&calc_load_nohz[idx], 0);
       return delta;
}
/*
 * NO_HZ can leave us missing all per-CPU ticks calling
 * calc_load_fold_active(), but since a NO_HZ CPU folds its delta into
 * calc_load_nohz per calc_load_nohz_start(), all we need to do is fold
 * in the pending NO_HZ delta if our NO_HZ period crossed a load cycle boundary.
 *
 * Once we've updated the global active value, we need to apply the exponential
 * weights adjusted to the number of cycles missed.
 */
static void calc_global_nohz(void)
{
       unsigned long sample_window;
       long delta, active, n;
       sample_window = READ_ONCE(calc_load_update);
       if (!time_before(jiffies, sample_window + 10)) {
              /*
               * Catch-up, fold however many we are behind still
               */
              delta = jiffies - sample_window - 10;
              n = 1 + (delta / LOAD_FREQ);
              active = atomic_long_read(&calc_load_tasks);
              active = active > 0 ? active * FIXED_1 : 0;
              avenrun[0] = calc_load_n(avenrun[0], EXP_1, active, n);
              avenrun[1] = calc_load_n(avenrun[1], EXP_5, active, n);
              avenrun[2] = calc_load_n(avenrun[2], EXP_15, active, n);
              WRITE_ONCE(calc_load_update, sample_window + n * LOAD_FREQ);
       }
       /*
        * Flip the NO_HZ index...
        *
        * Make sure we first write the new time then flip the index, so that
        * calc_load_write_idx() will see the new time when it reads the new
        * index, this avoids a double flip messing things up.
        */
       smp_wmb();
       calc_load_idx++;
}
#else /* !CONFIG_NO_HZ_COMMON */
static inline long calc_load_nohz_read(void) { return 0; }
static inline void calc_global_nohz(void) { }
#endif /* CONFIG_NO_HZ_COMMON */
/*
 * calc_load - update the avenrun load estimates 10 ticks after the
 * CPUs have updated calc_load_tasks.
 *
 * Called from the global timer code.
 */
void calc_global_load(void)
{
       unsigned long sample_window;
       long active, delta;
       sample_window = READ_ONCE(calc_load_update);
       if (time_before(jiffies, sample_window + 10))
              return;
       /*
        * Fold the 'old' NO_HZ-delta to include all NO_HZ CPUs.
        */
       delta = calc_load_nohz_read();
       if (delta)
              atomic_long_add(delta, &calc_load_tasks);
       active = atomic_long_read(&calc_load_tasks);
       active = active > 0 ? active * FIXED_1 : 0;
       avenrun[0] = calc_load(avenrun[0], EXP_1, active);
       avenrun[1] = calc_load(avenrun[1], EXP_5, active);
       avenrun[2] = calc_load(avenrun[2], EXP_15, active);
       WRITE_ONCE(calc_load_update, sample_window + LOAD_FREQ);
       /*
        * In case we went to NO_HZ for multiple LOAD_FREQ intervals
        * catch up in bulk.
        */
       calc_global_nohz();
}
/*
 * Called from scheduler_tick() to periodically update this CPU's
 * active count.
 */
void calc_global_load_tick(struct rq *this_rq)
{
       long delta;
       if (time_before(jiffies, this_rq->calc_load_update))
              return;
       delta  = calc_load_fold_active(this_rq, 0);
       if (delta)
              atomic_long_add(delta, &calc_load_tasks);
       this_rq->calc_load_update += LOAD_FREQ;
}

     解析如下:

  1、从上面的代码可知,定义的数组avenrun[]包含3个元素,分别用于存放past 1, 5 and 15 minutes的load average值。

  2、calc_load则是具体的计算函数,其参数ticks表示采样间隔。函数体中,获取当前的活跃进程数(active tasks),然后以其为参数,调用CALC_LOAD分别计算3种load average。

  3、通过calc_load_fold_active,可以看出,Load Average计算包括nr_running + nr_uninterruptible 等进程值。

  4、关于nr_running进程和nr_uninterruptible进程的计算方法,可以在源码树kernel/schde.c中看到相关代码以及include/linux/sched.h中看到CALC_LOAD的定义。

     关于Load Average 和 CPU util关系:

  •   Load Average :正在使用 CPU 进程 + 等待 CPU进程 +  等待 I/O 进程
  •  CPU Util:单位时间内 CPU 繁忙情况的统计,跟平均负载并不一定完全对应

    1、CPU 密集型进程:使用大量 CPU 会导致平均负载升高,此时这两者一致。

    2、I/O 密集型进程:等待 I/O 也会导致平均负载升高,但 CPU 使用率不一定很高。

    3、大量等待 CPU 的进程调度也会导致平均负载升高,此时 CPU 使用率也会比较高。

    可借助下图进一步说明2者之间的关联关系:

      最后,回到刚开始的问题:CPU使用率等同系统负载,或者直接反应系统负载情况,这种理解对吗?答案显而易见:“不完全对”。Load Average不仅体现CPU负载,磁盘I/O,内存不足也影响其实际负载情况。

相关实践学习
CentOS 7迁移Anolis OS 7
龙蜥操作系统Anolis OS的体验。Anolis OS 7生态上和依赖管理上保持跟CentOS 7.x兼容,一键式迁移脚本centos2anolis.py。本文为您介绍如何通过AOMS迁移工具实现CentOS 7.x到Anolis OS 7的迁移。
相关文章
|
7天前
|
Linux
在 Linux 系统中,“cd”命令用于切换当前工作目录
在 Linux 系统中,“cd”命令用于切换当前工作目录。本文详细介绍了“cd”命令的基本用法和常见技巧,包括使用“.”、“..”、“~”、绝对路径和相对路径,以及快速切换到上一次工作目录等。此外,还探讨了高级技巧,如使用通配符、结合其他命令、在脚本中使用,以及实际应用案例,帮助读者提高工作效率。
25 3
|
7天前
|
监控 安全 Linux
在 Linux 系统中,网络管理是重要任务。本文介绍了常用的网络命令及其适用场景
在 Linux 系统中,网络管理是重要任务。本文介绍了常用的网络命令及其适用场景,包括 ping(测试连通性)、traceroute(跟踪路由路径)、netstat(显示网络连接信息)、nmap(网络扫描)、ifconfig 和 ip(网络接口配置)。掌握这些命令有助于高效诊断和解决网络问题,保障网络稳定运行。
20 2
|
7天前
|
网络协议 网络安全 网络虚拟化
本文介绍了十个重要的网络技术术语,包括IP地址、子网掩码、域名系统(DNS)、防火墙、虚拟专用网络(VPN)、路由器、交换机、超文本传输协议(HTTP)、传输控制协议/网际协议(TCP/IP)和云计算
本文介绍了十个重要的网络技术术语,包括IP地址、子网掩码、域名系统(DNS)、防火墙、虚拟专用网络(VPN)、路由器、交换机、超文本传输协议(HTTP)、传输控制协议/网际协议(TCP/IP)和云计算。通过这些术语的详细解释,帮助读者更好地理解和应用网络技术,应对数字化时代的挑战和机遇。
35 3
|
7天前
|
安全 网络协议 Linux
本文详细介绍了 Linux 系统中 ping 命令的使用方法和技巧,涵盖基本用法、高级用法、实际应用案例及注意事项。
本文详细介绍了 Linux 系统中 ping 命令的使用方法和技巧,涵盖基本用法、高级用法、实际应用案例及注意事项。通过掌握 ping 命令,读者可以轻松测试网络连通性、诊断网络问题并提升网络管理能力。
24 3
|
9天前
|
安全 Linux 数据安全/隐私保护
在 Linux 系统中,查找文件所有者是系统管理和安全审计的重要技能。
在 Linux 系统中,查找文件所有者是系统管理和安全审计的重要技能。本文介绍了使用 `ls -l` 和 `stat` 命令查找文件所有者的基本方法,以及通过文件路径、通配符和结合其他命令的高级技巧。还提供了实际案例分析和注意事项,帮助读者更好地掌握这一操作。
27 6
|
10天前
|
Linux
在 Linux 系统中,`find` 命令是一个强大的文件查找工具
在 Linux 系统中,`find` 命令是一个强大的文件查找工具。本文详细介绍了 `find` 命令的基本语法、常用选项和具体应用示例,帮助用户快速掌握如何根据文件名、类型、大小、修改时间等条件查找文件,并展示了如何结合逻辑运算符、正则表达式和排除特定目录等高级用法。
36 6
|
6天前
|
监控 Java 应用服务中间件
高级java面试---spring.factories文件的解析源码API机制
【11月更文挑战第20天】Spring Boot是一个用于快速构建基于Spring框架的应用程序的开源框架。它通过自动配置、起步依赖和内嵌服务器等特性,极大地简化了Spring应用的开发和部署过程。本文将深入探讨Spring Boot的背景历史、业务场景、功能点以及底层原理,并通过Java代码手写模拟Spring Boot的启动过程,特别是spring.factories文件的解析源码API机制。
20 2
|
1月前
|
缓存 Java 程序员
Map - LinkedHashSet&Map源码解析
Map - LinkedHashSet&Map源码解析
67 0
|
1月前
|
算法 Java 容器
Map - HashSet & HashMap 源码解析
Map - HashSet & HashMap 源码解析
54 0
|
1月前
|
存储 Java C++
Collection-PriorityQueue源码解析
Collection-PriorityQueue源码解析
60 0

热门文章

最新文章