C언어

cpu 사용량

고요한하늘... 2012. 5. 4. 00:23

TOP 명령어에서 보이는 내용은 /proc/stat를 파싱한 결과라고 한다.

 

  • user: normal processes executing in user mode
  • nice: niced processes executing in user mode
  • system: processes executing in kernel mode
  • idle: twiddling thumbs
  • iowait: waiting for I/O to complete
  • irq: servicing interrupts
  • softirq: servicing softirqs

            from : http://www.linuxhowtos.org/System/procstat.htm


#include <string.h>

#include <stdio.h>

#include <stdlib.h>


void  get_cpu_info( char *cpu_info, int *total, int *idle )

{

        int num = 0;

        char *token, *bp;

        char buffer[1024];

        FILE *fp;

        if(( fp = fopen( "/proc/stat", "r" )) != NULL )

        {

                *total = 0;

                *idle  = 0;

                fgets( buffer, 1024, fp );

                for( token = strtok_r( buffer, " ", &bp ), num = 0; token != NULL; token = strtok_r( NULL, " ", &bp ), num++ )

                {

                        switch( num )

                        {

                                case 0 : break;

                                case 4 : *idle     = atoi(token);

                                default : (*total) += atoi(token); break;

                        }

                }

        }

}

int  calculate_cpu( int curr_idle, int curr_total , int prev_idle, int prev_total  )
{
        int diff_total;
        int diff_idle;
        int cpu;
        diff_idle  = curr_idle  - prev_idle;
        diff_total = curr_total - prev_total;
        cpu = (1000*(diff_total - diff_idle ) / diff_total+5)/10;
        return cpu;
}


int main()
{

        int curr_idle  = 0, prev_idle  = 0;
        int curr_total = 0, prev_total = 0;
        int  curr_percentage;
        char cpu_info[1024];
        while( 1 ){
                get_cpu_info( cpu_info, &curr_total, &curr_idle );
                curr_percentage = calculate_cpu( curr_idle, curr_total, prev_idle, prev_total );
                fprintf( stderr,"CPU = %d%%\n", curr_percentage );
                prev_total = curr_total;
                prev_idle  = curr_idle;
                sleep(1);
        }
}


'C언어' 카테고리의 다른 글

automake & autoconf  (0) 2012.06.18
external MERGE SORT  (0) 2012.05.24
환경변수 PATH_INFO 활용  (0) 2012.04.10
mkdir -p 구현  (0) 2012.03.22
STL 디버깅( DEBUGGING )  (0) 2011.12.07