linux下指定進程啟動並執行CPU__linux

來源:互聯網
上載者:User

    如果你覺得比核心的進程調度器更瞭解你的進程,不想過多的佔用CPU0,更高的快取命中,那麼可以設定進程運行在某個或某些CPU上。

   redis是單進程模型,為了充分利用多核伺服器效能,可以指定不同的redis執行個體運行在不同CPU上,這樣也可以減少進程環境切換。

   方法有兩種:

   一、使用命令taskset

   在RedHat系linux中,可以sudo yum privodes taskset尋找taskset在哪個包中,如下所示:

util-linux-2.23.2-26.el7.x86_64 : A collection of basic system utilities
Repo : @anaconda
Matched from:
Filename : /usr/bin/taskset
    可以知道是在util-linux-2.23.2-26.el7.x86_64,那麼sudo yum install util-linux就可以裝上。

      a.顯示進程運行在哪些CPU上

[zhujiang@localhost ~]$ ps aux | grep redis
root       2884  0.1  0.2  37260  5372 ?        Ssl  Mar10   3:53 /usr/local/bin/redis-server *:6379
zhujiang  17266  0.0  0.0 112648   956 pts/0    S+   05:57   0:00 grep --color=auto redis

[zhujiang@localhost ~]$ taskset -p 2884
pid 2884's current affinity mask: f
    顯示結果f表示二進位的1111,每一個1表示一個CPU,說明這個進程運行在4個CPU上,我這台虛擬機器正是四個CPU。

    b.指定進程運行在某CPU上

[zhujiang@localhost ~]$ sudo taskset -pc 2 2884
pid 2884's current affinity list: 0-3
pid 2884's new affinity list: 2
[zhujiang@localhost ~]$
註:2表示該進程只會運行在第3個CPU上(從0開始計數)

      c.進程啟動時指定CPU

[zhujiang@localhost ~]$ taskset -c 0 /usr/local/bin/redis-server

  

二、使用sched_setaffinity

#include <stdio.h>#include <time.h>#include <stdlib.h>#define __USE_GNU#include <sched.h>int main(){    int cpu_id = 1;    cpu_set_t mask;    CPU_ZERO(&mask);    CPU_SET(cpu_id, &mask);    if (sched_setaffinity(0, sizeof(mask), &mask) < 0)    {        perror("set affinity");        return -1;    }    struct timespec ts;    clock_gettime(CLOCK_MONOTONIC, &ts);    int now = ts.tv_sec;    int end = now + 20; //忙計算10秒    while (now < end)    {        clock_gettime(CLOCK_MONOTONIC, &ts);        now = ts.tv_sec;    }    CPU_ZERO(&mask);    cpu_id = 3;    CPU_SET(cpu_id, &mask);        if (sched_setaffinity(0, sizeof(mask), &mask) < 0)    {        perror("set affinity");        return -1;    }    clock_gettime(CLOCK_MONOTONIC, &ts);    now = ts.tv_sec;    end = now + 10;    while (now < end)    {        clock_gettime(CLOCK_MONOTONIC, &ts);        now = ts.tv_sec;    }    return 0;}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.