zoukankan      html  css  js  c++  java
  • linux CPU loading calculate

    http://hi.baidu.com/lionpanther/item/e908c37abdaf1c3f71442380

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>  
    struct occupy       
    {
       char name[20];      
       unsigned int user;  
       unsigned int nice;  
       unsigned int system;
       unsigned int idle; 
    };
    float g_cpu_used;          
    int cpu_num;               
    void cal_occupy(struct occupy *, struct occupy *); 
    void get_occupy(struct occupy *);


    int main()                  
    {
       struct occupy ocpu[10];   
       struct occupy ncpu[10];   
       int i;                    

       cpu_num = sysconf(_SC_NPROCESSORS_ONLN);
       for(;;)                            
       {  
          sleep(1);                       
          get_occupy(ocpu);                
          sleep(1);                       
          get_occupy(ncpu);                
          for (i=0; i<cpu_num; i++)         
          {
             cal_occupy(&ocpu[i], &ncpu[i]); 
             printf("%f ", g_cpu_used);    
          }
       }
    }
    void cal_occupy (struct occupy *o, struct occupy *n)
    {
       double od, nd;   
       double id, sd;   
       double scale;    
       od = (double) (o->user + o->nice + o->system +o->idle);//第一次(用户+优先级+系统+空闲)的时间
       nd = (double) (n->user + n->nice + n->system +n->idle);//第二次(用户+优先级+系统+空闲)的时间
       scale = 100.0 / (float)(nd-od);      
       id = (double) (n->user - o->user);   
       sd = (double) (n->system - o->system);
       g_cpu_used = ((sd+id)*100.0)/(nd-od);
    }
    void get_occupy (struct occupy *o)
    {
       FILE *fd;        
       int n;           
       char buff[1024];  
       fd = fopen ("/proc/stat", "r"); 
       fgets (buff, sizeof(buff), fd); 
       for(n=0;n<cpu_num;n++)          
       {
          fgets (buff, sizeof(buff),fd);
          sscanf (buff, "%s %u %u %u %u", &o[n].name, &o[n].user, &o[n].nice,&o[n].system, &o[n].idle);
          fprintf (stderr, "%s %u %u %u %u ", o[n].name, o[n].user, o[n].nice,o[n].system, o[n].idle);
       }
       fclose(fd);    
    }

  • 相关阅读:
    eureka流程图
    Feign和Ribbon的重试机制
    idea编译kafka 2.6 源码
    Feign的调用流程
    FeignClientFactoryBean创建动态代理
    Feign源码的入口
    Ribbon的检查服务
    Ribbon是怎么和Eureka整合的?
    Eureka过期
    backup: sqlHelper --cSharp
  • 原文地址:https://www.cnblogs.com/xiaotlili/p/3217249.html
Copyright © 2011-2022 走看看