Linux – 限制 Process 的 CPU 使用率

Loading

同事問了我一個問題在 Windows 的環境透過工作管理員(在 Process 按右鍵選擇 "設定相關性"),就可以限制 Proccess 只能使用某幾顆核心,那在 Linux 也有這樣的功能嗎??
cpu_limit01
恩!!真的不知道除了 #renice 和 #ulimit 外可以調整 Process 的優先順序外,好像真的沒有,不過在網路上有找到一個限制 CPU 使用率的工具.本篇是參考了下面這個網站的說明! http://www.cyberciti.biz/faq/cpu-usage-limiter-for-linux/

cpulimit

  • 一般安裝
    [root@benjr ~]# wget 'http://downloads.sourceforge.net/cpulimit/cpulimit-1.1.tar.gz'
    [root@benjr ~]# tar -zxvf cpulimit-1.1.tar.gz
    [root@benjr ~]# cd cpulimit-1.1
    [root@benjr ~]# make
    [root@benjr ~]# cp cpulimit /usr/local/sbin/
    [root@benjr ~]# rm -rf cpulimit*
    
  • yum 或是 apt-get 安裝
    [root@benjr ~]$ sudo apt-get install cpulimit
    

使用 cpulimit

限制的行程可以使用 Process ID 或是名稱,參數 -e 所使用的是 Process 名稱. -l 限制 CPU 的使用率.

[root@benjr ~]# cpulimit -e firefox -l 30

參數 -p 所使用的是 Process ID ( PID )

[root@benjr ~]# cpulimit -p 1313 -l 30

透過 ps 可以找到該程式的 Process ID ( PID )

[root@benjr ~]# ps aux | less 
[root@benjr ~]# ps aux | grep firefox

使用參數 P(大寫) 可以使用絕對路徑來做限制. 

[root@benjr ~]# cpulimit -P /opt/firefox/firebox -l 30

常用的參數

  • -p : Process PID.
  • -e : Process name.
  • -l : percentage of CPU allowed from 0 to 100.
  • -P: absolute path name of the executable program file.
  1. cpulimit project webpage 的建議1:
    Root vs Normal User Account
    cpulimit should run at least with the same user running the controlled process. But it is much better if you run cpulimit as root, in order to have a higher priority and a more precise control.
  2. cpulimit project webpage 的建議2: 
    A Note About SMP (Multicore / MultiCpu) Systems
    If your machine has one processor you can limit the percentage from 0% to 100%, which means that if you set for example 50%, your process cannot use more than 500 ms of cpu time for each second. But if your machine has four processors, percentage may vary from 0% to 400%, so setting the limit to 200% means to use no more than half of the available power. In any case, the percentage is the same of what you see when you run top.

不過這還是沒有解決要限制 Proccess 只能使用某幾顆核心的功能,有時間再上網查查看吧!!

可以使用 CPU affinity (taskset utility) 來限制 IO(Interrupt) 與 CPU , process ID (PID) 與 CPU 的使用,請參考 https://benjr.tw/99353 , 如果你的系統有 Non-Uniform Memory Access (NUMA) 功能也可以使用 #numactl 來指定 process ID (PID) 與 CPU ,關於 NUMA 請參考 https://benjr.tw/96788

沒有解決問題,試試搜尋本站其他內容

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料