pasckr 发表于 2016-5-9 15:44:35

如何在Ubuntu中绑定CPU进程?




                   现在科技在不断发展现在多CPU的趋势越来越大了. 有时候为了更好地操作机器,需要将某个进程绑定到具体的CPU上去。大家可能不能理解将进程绑定到CPU中运行是什么意思,简单的说就是进程/线程与cpu绑定,最直观的好处就是提高了cpucache的命中率,从而减少内存访问损耗,提高程序的速度,将普通进程变成核心进程。下面小编就像大家介绍在Ubuntu中怎么绑定CPU进程,Ubuntu(乌班图)是一个以桌面应用为主的Linux操作系统,和小编一起学习吧。
  在Ubuntu中绑定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 &
   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
  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
http://img14.3lian.com/201602/04/3e6d7a1899515637387061d544bab3c2.jpg  上面的视图可以看到,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
http://img14.3lian.com/201602/04/cdb07c9a5e214e0f82c4f2b9d0df4663.jpg  从上面的视图中可以看到6号CPU核的利用率为100%。
  随着CPU核的多个化,这样的绑定方法也是一样的,无论绑定哪个CPU核都能启动同样的效果,相信大家都追求运行的高速度,赶快来学习绑定CPU进程的方法吧!
页: [1]
查看完整版本: 如何在Ubuntu中绑定CPU进程?