如何让linux进程独占cpu运行,LINUX下如何指定进程运行的CPU

《性能调优攻略》在“多核CPU调优”章节提到“我们不能任由操作系统负载均衡,因为我们更了解自己的程序,所以,我们可以手动地为其分配CPU核,而不会过多地占用CPU0,或是让我们关键进程和一堆别的进程挤在一起。”。在文章中提到了Linux下的一个工具,taskset,可以设定单个进程运行的CPU。

下文,将会介绍taskset命令,schedtool命令以及sched_setaffinity系统调用,三者均可以指定进程运行的CPU实例。

1.taskset

taskset是LINUX提供的一个命令(ubuntu系统可能需要自行安装,schedutils

package)。他可以让某个程序运行在某个(或)某些CPU上。

1)显示进程运行的CPU

命令taskset -p 21184

显示结果:

pid 21184's current affinity mask: ffffff

注:显示结果的ffffff实际上是二进制24个低位均为1的bitmask,每个1对应于1个CPU,表示该进程在24个CPU上运行

2)指定进程运行在某个特定的CPU上

命令taskset -pc 3 21184

显示结果:

pid 21184's current affinity list: 0-23

pid 21184's new affinity list: 3

注:3表示CPU将只会运行在第4个CPU上(从0开始计数)。

3)进程启动时指定CPU

命令taskset -c 1 ./redis-server ../redis.conf

结合这上边三个例子,再看下taskset的manual,就比较清楚了。

OPTIONS

-p, --pid

operate on an existing PID and not launch a new task

-c, --cpu-list

specify a numerical list of processors instead of a bitmask. The

list may contain multiple items, separated by comma, and ranges.

For example, 0,5,7,9-11.

2.Debian提供了一个工具:schedtool(其他发行版还没有验证),可以使用他来设置一个pid的Affinity

Mask。

命令schedtool

-a 0x3f -e passthrough

3.sched_setaffinity系统调用

sched_setaffinity可以将某个进程绑定到一个特定的CPU。你比操作系统更了解自己的程序,为了避免调度器愚蠢的调度你的程序,或是为了在多线程程序中避免缓存失效造成的开销,你可能会希望这样做。

1//Short test program to test sched_setaffinity2//(which sets the affinity of processes to processors).3//Compile: gcc sched_setaffinity_test.c4//-o sched_setaffinity_test -lm5//Usage: ./sched_setaffinity_test6//7//Open a "top"-window at the same time and see all the work8//being done on CPU 0 first and after a short wait on CPU 1.9//Repeat with different numbers to make sure, it is not a10//coincidence.11//1213#include14#include15#include1617doublewaste_time(longn)18{19doubleres =0;20longi =0;21while(i200000) {22i++;23res +=sqrt (i);24}25returnres;26}2728intmain(intargc,char**argv)29{30unsignedlongmask =1;//processor 03132//bind process to processor 033if(sched_setaffinity(0,sizeof(mask), &mask) <0) {34perror("sched_setaffinity");35}3637//waste some time so the work is visible with "top"38printf ("result: %f\n", waste_time (2000));3940mask =2;//process switches to processor 1 now41if(sched_setaffinity(0,sizeof(mask), &mask) <0) {42perror("sched_setaffinity");43}4445//waste some more time to see the processor switch46printf ("result: %f\n", waste_time (2000));47}

根据你CPU的快慢,调整waste_time的参数。然后使用top命令,就可以看到进程在不同CPU之间的切换。(启动top命令后按“1”,可以看到各个CPU的情况)。

父进程和子进程之间会继承对affinity的设置。因此,大胆猜测,taskset实际上是首先执行了sched_setaffinity系统调用,然后fork+exec用户指定的进程。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值