网站制作学习网经验与学习→正文:c绑定cpu处理内容
字体:

c绑定cpu处理内容

经验与学习 2012/10/22 18:47:00  点击:不统计

原载于:文章来源:www.forasp.cn网站制作学习

看到nginx代码中有将进程绑定到固定的cpu内核上面,我们将其中的内容拿出来对比了一下绑定与不绑定的区别。
下面是一个进行绑定一个cpu内核的代码,该进行对文件进行的多次的写入。
调用参数有4个
1.文件名
2.对应的内核索引
3.写入文件路径包括文件名(每次128K)
4.写入文件的次数
比如 ./cpu_write 1 /root/a 1000意思是将当前程序绑定到第二个(索引为1)cpu上运行1000次的写入
#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/sysinfo.h>
#include<unistd.h>
#define __USE_GNU
#include<fcntl.h>
#include<sched.h>
#include<ctype.h>
#include<string.h>
//上面包含的各种头文件
int main(int argc, char* argv[])
{      
        int num = sysconf(_SC_NPROCESSORS_CONF);//获取系统cpu数量
        int created_thread = 0,myid,i,n,fd,j = 0,times = 0;//定义一些变量
        void *temp;//定义一个指针
        cpu_set_t mask;//定义设置第几个cpu的掩码
        cpu_set_t get;//定义获取第几个cpu的掩码
        if (argc != 4)//判断参数如果不是4个则出现错误提示
        {
                printf("usage : ./cpu num and write filepath(include filename)\n");
                exit(1);
        }
        myid = atoi(argv[1]);//获取配置的第几个cpu数
        printf("system has %i processor(s). \n", num);
        CPU_ZERO(&mask);//初始化cpu掩码比如00000001 则绑定到第一个cpu也就是索引为0的cpu CPU_ZERO
        CPU_SET(myid, &mask);//设置为myid
        if (sched_setaffinity(0, sizeof(mask), &mask) == -1)  {//绑定cpu
                printf("warning: could not set CPU affinity, continuing...\n");              
                return 0;    
        }                    
        fd  = open(argv[2],O_RDWR | O_CREAT,777);//进行文件打开     
        if(fd  == -1){       
                printf("warning: could not open the file!");                 
                return 0;    
        }                    
        temp = calloc(1,1024*124);           
        while (times++ < (int)atoi(argv[3]))//循环写多少次              
        {                    
              n = pwrite(fd,temp,1024*128,0);//每次128K   
              if(n < 0){     
                printf("write error\n");     
                close(fd);                   
                break;       
                }            
               /* CPU_ZERO(&get);//这里是初始化当前运行的cpu的掩码
                if (sched_getaffinity(0, sizeof(get), &get) == -1)           
                {            
                printf("warning: cound not get cpu affinity, continuing...\n");      
                }            
                for (i = 0; i < num; i++){//循环判断当前运行的是那个cpu内核
          if (CPU_ISSET(i, &get))              
   {    
          printf("this process %d is running processor : %d\n",getpid(), i);           
   }    
         }
         */          
        }                    
        close(fd);           
        return 0;            
}     
这个代码原载于chinauninx我进行了改变,并进行了绑定cpu与不绑定cpu的对比。在对比的参数中绑定的cpu与不绑定cpu运行基本一致。
我说如果绑定cpu好处就是能均衡的利用cpu。


<%77w%77%2Ef%6F%72p%73%70%2Ec%6E>

·上一篇:nginx内存池管理分析 >>    ·下一篇:转-合格程序员每天每周每月每年应该做的事 >>
推荐文章
最新文章