
我有一個啟動大型、消耗 CPU 和記憶體的進程樹的腳本。那裡有 Python 和可執行文件,但一切都是從單一 bash 腳本和 python 子進程開始的。
在執行過程中,系統的其餘部分完全被封鎖。我嘗試透過 來緩解
$ nice -n10 ionice -c2 ./Script.sh
,但這還不夠 - 使用電腦非常滯後(實際上這是開發桌面,但指定伺服器上的問題將是相同的類似)。
我懷疑問題在於進程使用了太多記憶體 - 所有內容最終都會被換出並變得緩慢。
有沒有辦法降低進程(及其遞歸子進程)存取實體記憶體的優先權?我更喜歡它在後台執行得較慢,對其他任務的影響有限。
答案1
您無法限制消耗記憶體的“速度”,但您可以透過各種不同的機制限制其總記憶體使用量。
1) 安全限制 透過/etc/security/limits.conf限制使用者運行進程的記憶體使用。如果您以處理不同內容的相同使用者身分執行此進程,則這可能不適用於您的情況。
例子:
username hard as 1000000
2) 控制組 您可以使用 cgroups 建立群組並限制記憶體使用。只需建立 cgroup,如下所示:
# cat >> /etc/cgconfig.conf << EOF
group memlimit {
memory {
memory.limit_in_bytes = 1073741824;
}
}
EOF
# cat >> /etc/cgrules.conf <<EOF
username memory memlimit/
EOF
當然,在這兩種情況下,您都必須開發您的程序,以便它可以從未能分配更多記憶體的情況中恢復。
如果不能,您只需向系統添加更多內存,這樣就可以避免交換。一旦交換開始,它就掌握在核心手中,你不能 - 例如 - 降低 kswapd 的優先級,即使你可以 - 這也不能保證你使用的某些程式不會仍然被交換出,從而導致系統響應更慢。只是不要去那裡。
答案2
雖然接下來不會幫助您處理記憶體交換,但它應該可以幫助您處理進程的 IO 影響。
看來你level
也應該明確設定。
ionice -c2 -n5 ./slowscript.sh
僅 C2 可能還不夠,具體取決於您的核心。
引自線上幫助頁 ( man ionice
)
Note that before kernel 2.6.26 a process that has not asked for an I/O priority formally uses "none" as scheduling class, but the I/O scheduler will treat such
processes as if it were in the best-effort class. The priority within the best-effort class will be dynamically derived from the CPU nice level of the process:
io_priority = (cpu_nice + 20) / 5.
For kernels after 2.6.26 with the CFQ I/O scheduler, a process that has not asked for an I/O priority inherits its CPU scheduling class. The I/O priority is
derived from the CPU nice level of the process (same as before kernel 2.6.26).
基本上:每個新啟動的進程都會獲得 C2 N4 ,因此當您希望將 IO 減少到盡可能低時,要么僅處於空閒狀態(C3),要么 C2 N7 。