<?xml version="1.0" encoding='utf-8'?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml">
<wml>
<card id="card1" title="Load (computing) - Page 27 - Wikipedia">
<p>
<a accesskey="1" href="page.php?w=Load_(computing)&amp;p=26">1.Previous</a><br />
<a accesskey="3" href="page.php?w=Load_%28computing%29&amp;p=28">3.Next</a>
</p>
<p>int | float, lavgs: dict[int, LoadEntry]):    """Initialize load averages based on linear interpolation of system load averages and instant load count."""    sys = getloadavg()    slopes = ((sys[0] - now) / 60, (sys[1] - sys[0]) / 240, (sys[2] - sys[1]) / 600)    for period in [10, 30, 60, 120, 300, 900, 1800, 3600]:        exp_factor = exp(-REFRESH_RATE / period)        if period < 60:            est_avg = now + slopes[0] * (period - 60)        elif period < 300:            est_avg = sys[0] + slopes[1] * (period - 300)        else:            est_avg = sys[1] + slopes[2] * (period - 900)        lavgs[period] = LoadEntry(avg=max(est_avg, 0), exp=exp_factor)</p>

<p>def update_loads(lavgs: dict[int, LoadEntry], current_load: int | float) -> None:    for _, entry in lavgs.items():        entry.avg = entry.avg * entry.exp + current_load * (1 - entry.exp)</p>

<p>if os.name == "posix":    uname = os.uname()[0].lower()    getloadavg = os.getloadavg</p>

<p>    if uname == "linux":        def get_current_load() -> int:            load = 0            with open("/proc/stat", "r") as f:                for line in f:                    if line.startswith("procs_running "):                        load += int(line.split()[1])  # Read procs_running                        load -= 1  # Subtract one for ourself                    elif line.startswith("procs_blocked ") and COUNT_DISKWAIT:                        load += int(line.split()[1])  # Read procs_blocked            return load</p>

<p>    else:        PS_THREAD_OPTION = "-H" if os.uname()[0].lower().endswith("bsd") else "-M"        PS_DISK_WAIT = "U" if os.uname()[0] == "Darwin" else "D"        PS_STATES = ("R" + PS_DISK_WAIT) if COUNT_DISKWAIT else "R"</p>

<p>        def get_current_load() -> int:            with os.popen(f"ps {PS_THREAD_OPTION}ax -o stat", "r") as f:                states = map(f, lambda line: line.split()[-1])  # Get the last column. Required on macOS!                return sum(1 if state[0] in PS_STATES else 0 for state in states) - 1</p>

<p>elif os.name == "nt":    # It is possible to use Windows performance counters to get a queue length.    # In fact, Microsoft recommends it as an additional metric for load in addition to CPU usage:    # https://learn.microsoft.com/en-us/biztalk/technical-guides/using-the-performance-analysis-of-logs-pal-tool#processor-queue-length-analysis    # Using it we can also obtain a load similar to Unix systems.    from pyperfmon import pyperfmon</p>

<p>    pm = pyperfmon.pyperfmon()    ncores = os.cpu_count()    get_counter = lambda x: pm.getCounter(x)</p>

<p>    def get_current_load() -> float:        return (            # Threads waiting for CPU, not running ones            get_counter(r"System\Processor Queue Length")            # Approximate number of threads using CPU            + get_counter(r"Processor\_Total\% Processor Time") * ncores            # Threads waiting for disk I/O            + get_counter(r"PhysicalDisk\_Total\Current Disk Queue Length")            if COUNT_DISKWAIT            else 0        )</p>

<p>    def getloadavg() -> tuple[float, float, float]:        # Dummy implementation for Windows        load = get_current_load()        return (load, load, load)</p>

<p>def main():    lavgs: dict[int, LoadEntry] = {}    current_load = get_current_load()    initialize_loads(current_load, lavgs)    heading = ["SYSTIME", " CURR"] + [str(x) for x in PERIODS]    print("\t".join(heading))    while True:        # Always print before recalculating        entries = [f"{datetime.now().strftime('%H:%M:%S')}  {current_load:.4f}"]        entries += [f"{entry.avg:.4f}" for entry in lavgs.values()]        print("\t".join(entries), flush=True)</p>

<p>        # Sleep and wait. This assumes that the time used to update a new line is        # minuscule compared to the time slept. If this is not the case, a        # sleepuntil()-type reckoning should be used.        time.sleep(REFRESH_RATE)</p>

<p>        # Print        current_load = get_current_load()        update_loads(lavgs, current_load)</p>

<p>if __name__ == "__main__":    main()</p>

<p></p>

<p><big> Other system performance commands </big></p>
<p>Other commands for assessing system performance include:</p>

<p>
* <code><a href="page.php?w=uptime">uptime</a></code> the system reliability and load average<br/>
* <code><a href="page.php?w=top_%28software%29">top</a></code> for an overall system view<br/>
** <code><a href="page.php?w=htop">htop</a></code> interactive process viewer<br/>
* <code>btop</code> another overall system view tool<br/>
* <code><a href="page.php?w=vmstat">vmstat</a></code> vmstat reports information about runnable or blocked processes, memory, paging, block I/O, traps, and CPU.<br/>
* <code>dool</code> (formerly <code>dstat</code>), <code>atop</code> helps correlate all existing resource data for processes, memory, paging, block I/O, traps, and CPU activity.<br/>
* <code><a href="page.php?w=iftop">iftop</a></code> interactive network traffic viewer per interface<br/>
* <code>nethogs</code> interactive network traffic viewer per process<br/>
* <code>iotop</code> interactive I/O viewer<br/>
* <code><a href="page.php?w=iostat">iostat</a></code> for storage I/O statistics<br/>
* <code><a href="page.php?w=netstat">netstat</a></code> for network statistics<br/>
* <code><a href="page.php?w=mpstat">mpstat</a></code> for CPU statistics<br/>
* <code>tload</code> load average graph for terminal<br/>
* <code><a href="page.php?w=xload">xload</a></code> load average graph for X</p>

<p><big> See also </big></p>
<p>
* <a href="page.php?w=CPU_usage">CPU usage</a></p>

<p><big>Notes</big></p>
<p><big> References </big></p>
<p><big> External links </big></p>
<p>
* <br/>
*                                       <br/>
*  Explanation using an illustrated traffic analogy.<br/>
* <br/>
* </p>

<p></p>
<p>
<a accesskey="1" href="page.php?w=Load_(computing)&amp;p=26">1.Previous</a><br />
<a accesskey="3" href="page.php?w=Load_%28computing%29&amp;p=28">3.Next</a>
</p>

<do type="prev" label="Search">
        <go href="search.wml"/>
</do>

</card>
</wml>
