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,内存不足也影响其实际负载情况。

相关文章
|
1月前
|
缓存 监控 Linux
Linux系统清理缓存(buff/cache)的有效方法。
总结而言,在大多数情形下你不必担心Linux中buffer与cache占用过多内存在影响到其他程序运行;因为当程序请求更多内存在没有足够可用资源时,Linux会自行调整其占有量。只有当你明确知道当前环境与需求并希望立即回收这部分资源给即将运行重负载任务之前才考虑上述方法去主动干预。
706 10
|
1月前
|
安全 Linux 数据安全/隐私保护
为Linux系统的普通账户授予sudo访问权限的过程
完成上述步骤后,你提升的用户就能够使用 `sudo`命令来执行管理员级别的操作,而无需切换到root用户。这是一种更加安全和便捷的权限管理方式,因为它能够留下完整的权限使用记录,并以最小权限的方式工作。需要注意的是,随意授予sudo权限可能会使系统暴露在风险之中,尤其是在用户不了解其所执行命令可能带来的后果的情况下。所以在配置sudo权限时,必须谨慎行事。
308 0
|
1月前
|
Ubuntu Linux 开发者
国产 Linux 发行版再添新成员,CutefishOS 系统简单体验
当然,系统生态构建过程并不简单,不过为了帮助国产操作系统优化生态圈,部分企业也开始用国产操作系统替代 Windows,我们相信肯定会有越来越多的精品软件登录 Linux 平台。
106 0
|
1月前
|
Ubuntu 安全 Linux
Linux系统入门指南:从零开始学习Linux
Shell脚本是一种强大的自动化工具,可以帮助您简化重复的任务或创建复杂的脚本程序。了解Shell脚本的基本语法和常用命令,以及编写和运行Shell脚本的步骤,将使您更高效地处理日常任务。
199 0
|
1月前
|
Ubuntu Linux 图形学
Linux学习之Linux桌面系统有哪些?
Cinnamon:与MATE类似,Cinnamon 拥有 GNOME 和 Unity 等其它桌面环境所没有的种种功能,是高度可定制的桌面环境,不需要任何外部插件、窗口组件和调整工具来定制桌面。
113 0
|
10月前
|
监控 Java 应用服务中间件
高级java面试---spring.factories文件的解析源码API机制
【11月更文挑战第20天】Spring Boot是一个用于快速构建基于Spring框架的应用程序的开源框架。它通过自动配置、起步依赖和内嵌服务器等特性,极大地简化了Spring应用的开发和部署过程。本文将深入探讨Spring Boot的背景历史、业务场景、功能点以及底层原理,并通过Java代码手写模拟Spring Boot的启动过程,特别是spring.factories文件的解析源码API机制。
267 2
|
6月前
|
算法 测试技术 C语言
深入理解HTTP/2:nghttp2库源码解析及客户端实现示例
通过解析nghttp2库的源码和实现一个简单的HTTP/2客户端示例,本文详细介绍了HTTP/2的关键特性和nghttp2的核心实现。了解这些内容可以帮助开发者更好地理解HTTP/2协议,提高Web应用的性能和用户体验。对于实际开发中的应用,可以根据需要进一步优化和扩展代码,以满足具体需求。
637 29
|
6月前
|
前端开发 数据安全/隐私保护 CDN
二次元聚合短视频解析去水印系统源码
二次元聚合短视频解析去水印系统源码
184 4
|
6月前
|
JavaScript 算法 前端开发
JS数组操作方法全景图,全网最全构建完整知识网络!js数组操作方法全集(实现筛选转换、随机排序洗牌算法、复杂数据处理统计等情景详解,附大量源码和易错点解析)
这些方法提供了对数组的全面操作,包括搜索、遍历、转换和聚合等。通过分为原地操作方法、非原地操作方法和其他方法便于您理解和记忆,并熟悉他们各自的使用方法与使用范围。详细的案例与进阶使用,方便您理解数组操作的底层原理。链式调用的几个案例,让您玩转数组操作。 只有锻炼思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
6月前
|
移动开发 前端开发 JavaScript
从入门到精通:H5游戏源码开发技术全解析与未来趋势洞察
H5游戏凭借其跨平台、易传播和开发成本低的优势,近年来发展迅猛。接下来,让我们深入了解 H5 游戏源码开发的技术教程以及未来的发展趋势。