centos7限制CPU使用率-cpulimit


centos7限制CPU使用率-cpulimit

一、背景

有的進程長時間占用CPU較大,拖垮了其他進程。所以有必要限制CPU的使用率

二、CPU使用率限制方案

采用以下工具限制CPU使用率:

  1. 開源工具cpulimit
  2. shell腳本實現

三、操作

(一)安裝cpulimit

1、下載

優先下載:https://sourceforge.net/projects/cpulimit/

如果不能下載了,使用備用源文件:https://www.cnblogs.com/andy9468/p/15357524.html

項目地址:https://hub.fastgit.org/opsengine/cpulimit/releases

2、編譯、安裝

https://blog.csdn.net/weixin_34061482/article/details/90595276

tar -zcvf cpulimit-1.1.tar.gz
cd cpulimit-1.1
make

# 安裝
cp cpulimit /usr/bin
chmod 777 /usr/bin/cpulimit

3、測試

cpulimit --help

4、cpulimit的常見使用

https://blog.csdn.net/weixin_39731623/article/details/111763124
https://www.cnblogs.com/luruiyuan/p/12676758.html

# 將pid為39929的進程,cpu的使用率限制到50%以內
cpulimit -p 39929 -l 50

(二)編寫shell腳本、編寫測試腳本

1、shell限制腳本

# 限制CPU占用率大於50%的進程
for x in `ps -aux|awk '{if($3 > 50) print $2}'`; do cpulimit -p $x -l 50; done

展開解釋

for x in `ps -aux|awk '{if($3 > 50) print $2}'`; 
do 
	cpulimit -p $x -l 50; 
done

當某些進程的CPU占用(第3列)率大於50%時,取出進程pid號(第2列),在for循環中將其CPU的使用率限制到50%以內。

2、python測試腳本

cpu_test.py

import os
import time


def add2():
    sum_int = 1
    start_time = time.time()
    for i in range(1000000):
        sum_int = sum_int * (i + 1)
        pass
    end_time = time.time()
    use_time = end_time - start_time
    print("進程id: %s use_time: %s" % (os.getpid(), use_time))
    print(sum_int)


if __name__ == '__main__':
    add2()

(三)測試CPU限制效果

1、啟動python測試腳本

python3 cpu_test.py

提示:當python3進程被限制使用CPU后,會被放到后台運行。解除限制后,fg命令多次,可以調出改進程。

2、啟動shell限制腳本

for x in `ps -aux|awk '{if($3 > 50) print $2}'`; do cpulimit -p $x -l 50; done

3、htop觀察CPU占用情況

htop


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM