博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
linux:如何指定进程运行的CPU
阅读量:4028 次
发布时间:2019-05-24

本文共 2147 字,大约阅读时间需要 7 分钟。

http://www.cnblogs.com/liuhao/archive/2012/06/21/2558069.html 

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

同时,因为最近在看redis的相关资料,redis作为单进程模型的程序,为了充分利用多核CPU,常常在一台server上会启动多个实例。而为了减少切换的开销,有必要为每个实例指定其所运行的CPU。

 

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

1.taskset

taskset是LINUX提供的一个命令(ubuntu系统可能需要自行安装,schedutils package)。他可以让某个程序运行在某个(或)某些CPU上。

以下均以redis-server举例。

1)显示进程运行的CPU

命令taskset -p 21184

显示结果:

pid 21184's current affinity mask: ffffff

注:21184是redis-server运行的pid

      显示结果的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.sched_setaffinity系统调用

如下文章部分翻译自:

问题描述

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

1 /* Short test program to test sched_setaffinity 2 * (which sets the affinity of processes to processors). 3 * Compile: gcc sched_setaffinity_test.c 4 *              -o sched_setaffinity_test -lm 5 * Usage: ./sched_setaffinity_test 6 * 7 * Open a "top"-window at the same time and see all the work 8 * 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 */12  13 #include 
14 #include
15 #include
16  17 double waste_time(long n)18 {19     double res = 0;20     long i = 0;21     while(i

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

 

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

你可能感兴趣的文章
微信小程序开发全线记录
查看>>
Centos import torchvision 出现 No module named ‘_lzma‘
查看>>
网页设计里的浮动 属性
查看>>
Maximum Subsequence Sum
查看>>
PTA:一元多项式的加乘运算
查看>>
CCF 分蛋糕
查看>>
解决python2.7中UnicodeEncodeError
查看>>
小谈python 输出
查看>>
Django objects.all()、objects.get()与objects.filter()之间的区别介绍
查看>>
python:如何将excel文件转化成CSV格式
查看>>
Django 的Error: [Errno 10013]错误
查看>>
机器学习实战之决策树(一)
查看>>
[LeetCode By Python] 2 Add Two Number
查看>>
python 中的 if __name__=='__main__' 作用
查看>>
机器学习实战之决策树二
查看>>
[LeetCode By Python]7 Reverse Integer
查看>>
[LeetCode By Python]9. Palindrome Number
查看>>
[leetCode By Python] 14. Longest Common Prefix
查看>>
[LeetCode By Python]107. Binary Tree Level Order Traversal II
查看>>
[LeetCode By Python]108. Convert Sorted Array to Binary Search Tree
查看>>