歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Ubuntu系統進程綁定CPU核

Ubuntu系統進程綁定CPU核

日期:2017/2/28 13:59:27   编辑:Linux教程

本文講述如何在Ubuntu系統中,把指定的進程綁定到指定的CPU核運行。而通常是由操作系統負責管理進程和線程的調度,但是這種情況下是不清楚由哪個CPU核運行你的進程,因為操作系統的調度是基於資源的可用性進行判斷的。

可以這樣,把指定的CPU核綁定到你的進程。

taskset -cp <CPU ID | CPU IDs> <Process ID>

下面用一個簡單的例子來說明怎樣做到。

1. CPU利用率達100%的樣例代碼:

class Test {
    public static void main(String args[]) {
        int i = 0;
        while (true) {
            i++;
        }
    }
}

2. 編譯並運行上面的樣例代碼

# javac Test.java
# java Test &
[1] 26531

3. 使用htop命令查看CPU的利用率

如果未安裝htop工具,執行下面的命令:

# apt-get install htop
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following NEW packages will be installed:
  htop
0 upgraded, 1 newly installed, 0 to remove and 41 not upgraded.
Need to get 66.9 kB of archives.
After this operation, 183 kB of additional disk space will be used.
Get:1 http://mirrors.163.com/ubuntu/ precise/universe htop amd64 1.0.1-1 [66.9 kB]
Fetched 66.9 kB in 0s (163 kB/s)
Selecting previously unselected package htop.
(Reading database ... 57100 files and directories currently installed.)
Unpacking htop (from .../htop_1.0.1-1_amd64.deb) ...
Processing triggers for man-db ...
Setting up htop (1.0.1-1) ...

安裝完成後,執行命令:

# htop


上面的視圖可以看到,CPU2的利用率達到100%,且這個進程有可能被分配到其它CPU核上運行,這個分配是不定的。

4. 進程綁定CPU核

運行以下命令,把此Java進程(進程ID號為26502)永久的分配給5號CPU核(CPU核號從0開始計算,因此序號4指的是5號CPU核)

# taskset -cp 5 26531
pid 26531's current affinity list: 0-7
pid 26531's new affinity list: 5


從上面的視圖中可以看到6號CPU核的利用率為100%。

更多Ubuntu相關信息見Ubuntu 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=2

Copyright © Linux教程網 All Rights Reserved