[AIX 성능 도구 7] perfstat API (2) 구성 요소별 인터페이스와 CPU

핵심 정리

  • 구성 요소별 인터페이스는 프로세서, 디스크, 네트워크 인터페이스, 페이징 공간 같은 개별 구성 요소의 지표를 돌려줍니다. 이름은 perfstat_subsystem 형식입니다.
  • 공통 형태: perfstat_xxx(&name, buf, sizeof(perfstat_xxx_t), 개수). name에 ""나 FIRST_CPU 같은 매크로를 주면 첫 구성 요소부터 읽고, 돌아온 name이 다음 위치입니다.
  • name·userbuff를 NULL, 개수를 0으로 주면 전체 구조체 수를 돌려줍니다. 그 수만큼 메모리를 잡고 한 번에 읽는 두 번 호출 방식이 효율적입니다.
  • perfstat_cpu는 ncpus_high개를 돌려주므로 꺼지거나 옮겨진 CPU가 섞입니다. 두 호출 사이 틱 합이 같으면 그 CPU는 구간 내내 오프라인입니다.
  • (6.1) perfstat_cpu_util은 두 번의 원래 값(perfstat_rawdata_t)으로 사용률(%)을 계산해 줍니다. UTIL_CPU_TOTAL은 시스템 전체, UTIL_CPU는 CPU별입니다.
항목 내용
버전 AIX 5.3, AIX 6.1 (6.1에서 HFI, perfstat_cpu_util, 프로세스·스레드 인터페이스가 더해짐)
원문 Performance Tools Guide and Reference — 5.3판 6장(155158쪽), 6.1판 100123쪽
파일 /usr/include/libperfstat.h, /usr/samples/libperfstat
관련 명령어 mpstat, lparstat, sar

구성 요소별(component-specific) 인터페이스는 시스템의 개별 구성 요소(프로세서, 디스크, 네트워크 인터페이스, 페이징 공간 등)에 관한 지표를 보고합니다.

다음 AIX 인터페이스는 모두 perfstat_subsystem이라는 이름 규칙과 공통 형태를 씁니다.

인터페이스 설명
perfstat_cpu 개별 프로세서 사용 지표. 참고: WPAR 안의 응용 프로그램에서 부르면 전역 값을 돌려줍니다.
perfstat_disk 개별 디스크 사용 지표. 참고: WPAR 안에서 부르면 데이터를 돌려주지 않습니다.
perfstat_diskpath 개별 디스크 경로 지표. 참고: WPAR 안에서 부르면 데이터를 돌려주지 않습니다.
perfstat_diskadapter 개별 디스크 어댑터 지표. 참고: WPAR 안에서 부르면 데이터를 돌려주지 않습니다.
perfstat_netinterface 개별 네트워크 인터페이스 지표. 참고: WPAR 안에서 부르면 그 WPAR의 데이터를 돌려줍니다.
perfstat_protocol 개별 네트워크 프로토콜 관련 지표. 참고: WPAR 안에서 부르면 그 WPAR의 데이터를 돌려줍니다.
perfstat_netbuffer 개별 네트워크 버퍼 할당 지표. 참고: WPAR 안에서 부르면 그 WPAR의 데이터를 돌려줍니다.
perfstat_pagingspace 개별 페이징 공간 지표. 참고: WPAR 안에서 부르면 데이터를 돌려주지 않습니다.
perfstat_memory_page 여러 페이지 크기의 사용 지표. 참고: WPAR 안에서 부르면 전역 값을 돌려줍니다.
perfstat_tape 개별 테이프 사용 지표. 참고: WPAR 안에서 부르면 데이터를 돌려주지 않습니다.
perfstat_logicalvolume 개별 논리 볼륨 사용 지표. 참고: WPAR 안에서 부르면 데이터를 돌려주지 않습니다.
perfstat_volumegroup 개별 볼륨 그룹 사용 지표. 참고: WPAR 안에서 부르면 데이터를 돌려주지 않습니다.
perfstat_hfistat (6.1) 개별 HFI(host fabric interface) 통계
perfstat_hfistat_window (6.1) 개별 창(window) 기반 HFI 통계
perfstat_cpu_util (6.1) CPU 사용률을 계산합니다.
perfstat_process (6.1) 프로세스 사용 지표
perfstat_process_util (6.1) 프로세스 사용 지표를 계산합니다.
perfstat_thread (6.1) 커널 스레드 사용 지표
perfstat_thread_util (6.1) 커널 스레드 사용 지표를 계산합니다.

perfstat_memory_page와 perfstat_hfistat_window를 뺀 모든 구성 요소 인터페이스의 공통 형태는 다음과 같습니다.

text
int perfstat_subsystem(perfstat_id *name,
                       perfstat_subsystem_t * userbuff,
                       int sizeof_struct,
                       int desired_number);

perfstat_memory_page의 형태는 다음과 같습니다.

text
int perfstat_memory_page(perfstat_psize_t *psize ,
     perfstat_subsystem_t * userbuff,
     int sizeof_struct,
     int desired_number);

perfstat_hfistat_window의 형태는 다음과 같습니다.

text
int perfstat_hfistat_window(perfstat_id_window_t *name,
         perfstat_hfistat_window_t *userbuff,
         int sizeof_struct,
         int desired_number);

모든 인터페이스의 매개변수 사용법은 다음과 같습니다.

매개변수 설명
perfstat_id_t *name 통계를 얻을 첫 구성 요소 이름(예: perfstat_disk()이면 hdisk2). 할당 오류를 피하고 사용자가 상수 문자열을 매개변수로 주지 못하게 하려고 char * 인수를 바로 넘기는 대신 char * 필드가 든 구조체를 씁니다. 하위 시스템의 첫 구성 요소부터 시작하려면 name 매개변수의 char* 필드를 ""(빈 문자열)로 설정합니다. libperfstat.h에 정의된 FIRST_SUBSYSTEM 같은 매크로(예: FIRST_CPU)를 쓸 수 있습니다.
perfstat_id_window_t *name (6.1) "name->name" 필드에 HFI 이름(예: hfi0, hfi1, FIRST_HFI)을, "name->windowid" 필드에 HFI 창 번호를 넣습니다.
perfstat_subsystem_t *userbuff 돌려받을 구조체들이 들어갈 공간이 충분한 메모리 영역의 포인터
int sizeof_struct sizeof(perfstat_subsystem_t)로 설정합니다.
int desired_number userbuff에 돌려받을 perfstat_subsystem_t 구조체 수

오류가 나면 -1을 돌려줍니다. 그렇지 않으면 복사한 구조체 수를 돌려줍니다. name 필드는 NULL이나 다음에 쓸 수 있는 구조체의 이름으로 설정됩니다.

예외로 name=NULL, userbuff=NULL, desired_number=0이면 쓸 수 있는 구조체의 전체 수를 돌려줍니다.

어떤 유형의 구조체를 모두 가져오려면 먼저 구조체 수를 알아내 필요한 메모리를 잡은 다음, 해당 API를 한 번 불러 모든 구조체를 가져옵니다. 다른 방법은 고정된 개수의 구조체를 잡아 두고, 매번 앞 호출이 돌려준 name을 넘기며 API를 되풀이해 다음 묶음을 가져오는 것입니다. 이때는 name을 ""나 FIRST_SUBSYSTEM으로 시작해 되풀이합니다.

API 호출 수와 시스템 호출 수를 줄일수록 코드가 효율적이므로 두 번 호출 방식이 좋습니다. 다음 절의 예 가운데 일부는 두 번 호출 방식을 씁니다. 두 번 호출 방식은 메모리를 많이 잡으므로 여러 번 호출 방식을 쓰기도 하며, 이것도 다음 예에 나옵니다.

다음 절들에서 인터페이스마다 돌려주는 데이터의 종류와 코드 예를 보여 줍니다.

영어 원문

Component-Specific interfaces

Component-specific interfaces report metrics related to individual components on a system (such as a processor, disk, network interface, or paging space).

All of the following AIX interfaces use the naming convention perfstat_subsystem, and use a common signature:

  • perfstat_cpu — Retrieves individual processor usage metrics Note: This interface returns global values when called by an application running inside WPAR.
  • perfstat_disk — Retrieves individual disk usage metrics Note: This interface does not return any data when called by an application running inside WPAR
  • perfstat_diskpath — Retrieves individual disk path metrics Note: This interface does not return any data when called by an application running inside WPAR
  • perfstat_diskadapter — Retrieves individual disk adapter metrics Note: This interface does not return any data when called by an application running inside WPAR.
  • perfstat_netinterface — Retrieves individual network interfaces metrics Note: This interface returns WPAR-specific data when called by an application running inside WPAR.
  • perfstat_protocol — Retrieves individual network protocol-related metrics Note: This interface returns WPAR-specific data when called by an application running inside WPAR.
  • perfstat_netbuffer — Retrieves individual network buffer allocation metrics Note: This interface returns WPAR-specific data when called by an application running inside WPAR.
  • perfstat_pagingspace — Retrieves individual paging space metrics Note: This interface does not return any data when called by an application running inside WPAR.
  • perfstat_memory_page — Retrieves multiple page size usage metrics Note: This interface returns global values when it is called by an application running inside a WPAR.
  • perfstat_tape — Retrieves individual tape usage metrics Note: This interface does not return any data when it is called by an application running inside a WPAR.
  • perfstat_logicalvolume — Retrieves individual logical volume usage metrics Note: This interface does not return any data when called it is by an application running inside a WPAR.
  • perfstat_volumegroup — Retrieves individual volume group usage metrics Note: This interface does not return any data when it is called by an application running inside a WPAR.
  • perfstat_hfistat — Retrieves individual host fabric interface (HFI) statistics.
  • perfstat_hfistat_window — Retrieves individual window-based HFI statistics.
  • perfstat_cpu_util — Calculates CPU utilization
  • perfstat_process — Retrieves process utilization metrics
  • perfstat_process_util — Calculates process utilization metrics
  • perfstat_thread — Retrieves kernel thread utilization metrics
  • perfstat_thread_util — Calculates kernel thread utilization metrics

The common signature used by all the component interfaces except perfstat_memory_page and perfstat_hfistat_window is as follows:

text
int perfstat_subsystem(perfstat_id *name,
                       perfstat_subsystem_t * userbuff,
                       int sizeof_struct,
                       int desired_number);

The perfstat_memory_page uses the following signature:

text
int perfstat_memory_page(perfstat_psize_t *psize ,
     perfstat_subsystem_t * userbuff,
     int sizeof_struct,
     int desired_number);

The perfstat_hfistat_window uses the following signature:

text
int perfstat_hfistat_window(perfstat_id_window_t *name,
         perfstat_hfistat_window_t *userbuff,
         int sizeof_struct,
         int desired_number);

The usage of the parameters for all of the interfaces is as follows:

  • perfstat_id_t *name — Enter the name of the first component (for example hdisk2 for perfstat_disk()) to obtain the statistics. A structure containing a char * field is used instead of directly passing a char * argument to the function to avoid allocation errors and to prevent the user from giving a constant string as parameter. To start from the first component of a subsystem, set the char* field of the name parameter to "" (empty string). You can use macros such as FIRST_SUBSYSTEM (for example, FIRST_CPU) defined in the libperfstat.h file.
  • perfstat_id_window_t *name — Enter the Host Fabric Interface name (for example, hfi0 or hfi1 or FIRST_HFI) in the "name->name" field, and the HFI window number in "name->windowid" field.
  • perfstat_subsystem_t *userbuff — Specifies a pointer to a memory area with enough space for the returned structures.
  • int sizeof_struct — Set the parameter to sizeof(perfstat_subsystem_t).
  • int desired_number — Specifies the number of structures of type perfstat_subsystem_t to return in userbuff.

The return value is -1 in case of error. Otherwise, the number of structures copied is returned. The field name is either set to NULL or to the name of the next structure available.

An exception to this scheme is when name=NULL, userbuff=NULL and desired_number=0, the total number of structures available is returned.

To retrieve all structures of a given type, find the number of structures and allocate the required memory to hold the structures. You must then call the appropriate API to retrieve all structures in one call. Another method is to allocate a fixed set of structures and repeatedly call the API to get the next set of structures, each time passing the name returned by the previous call. Start the process with the name set to "" or FIRST_SUBSYSTEM, and repeat the process.

Minimizing the number of API calls, and the number of system calls, leads to more efficient code, so the two-call approach is preferred. Some of the examples shown in the following sections illustrate the API usage using the two-call approach. The two-call approach causes large amount of memory allocation, the multiple-call approach is sometimes used, and is illustrated in the following examples.

The following sections provide examples of the type of data returned and the code used for each of the interfaces.

perfstat_cpu 인터페이스

perfstat_cpu 인터페이스는 libperfstat.h 파일에 정의된 perfstat_cpu_t 구조체 묶음을 돌려줍니다.

perfstat_cpu_t 구조체의 주요 필드는 다음과 같습니다.

필드 설명
name 논리 프로세서 이름(cpu0, cpu1, …)
user 사용자 모드에서 쓴 클록 틱 수
sys 시스템(커널) 모드에서 쓴 클록 틱 수
idle 대기 중인 I/O 없이 유휴 상태로 쓴 클록 틱 수
wait 대기 중인 I/O가 있는 채 유휴 상태로 쓴 클록 틱 수
syscall 실행한 시스템 호출 수

이 밖에도 CPU 관련 지표(fork, read, write, exec 수 등)를 돌려줍니다. 전체 목록은 libperfstat.h 헤더의 perfstat_cpu_t 부분을 봅니다.

다음 코드는 perfstat_cpu 인터페이스를 쓰는 예입니다.

text
#include <stdio.h>
#include <stdlib.h>
#include <libperfstat.h>
int main(int argc, char *argv[]) {
   int i, retcode, cputotal;
   perfstat_id_t firstcpu;
   perfstat_cpu_t *statp;
   /* check how many perfstat_cpu_t structures are available */
   cputotal =  perfstat_cpu(NULL, NULL, sizeof(perfstat_cpu_t), 0);
      /* check for error */
   if (cputotal <= 0)
   {
        perror("perfstat_cpu");
        exit(-1);
   }
   /* allocate enough memory for all the structures */
   statp = calloc(cputotal,sizeof(perfstat_cpu_t));
   if(statp==NULL){
 printf("No sufficient memory\n");
 exit(-1);
   }
   /* set name to first cpu */
   strcpy(firstcpu.name, FIRST_CPU);
   /* ask to get all the structures available in one call */
   retcode = perfstat_cpu(&firstcpu, statp, sizeof(perfstat_cpu_t), cputotal);
   /* check for error */
   if (retcode <= 0)
   {
        perror("perfstat_cpu");
        exit(-1);
   }
   /* return code is number of structures returned */
   for (i = 0; i < retcode; i++) {
      printf("\nStatistics for CPU : %s\n", statp[i].name);
      printf("------------------\n");
      printf("CPU user time (raw ticks)  : %llu\n", statp[i].user);
      printf("CPU sys  time (raw ticks)  : %llu\n", statp[i].sys);
      printf("CPU idle time (raw ticks)  : %llu\n", statp[i].idle);
      printf("CPU wait time (raw ticks)  : %llu\n", statp[i].wait);
      printf("number of syscalls         : %llu\n", statp[i].syscall);
      printf("number of readings         : %llu\n", statp[i].sysread);
      printf("number of writings         : %llu\n", statp[i].syswrite);
      printf("number of forks            : %llu\n", statp[i].sysfork);
      printf("number of execs            : %llu\n", statp[i].sysexec);
      printf("number of char read        : %llu\n", statp[i].readch);
      printf("number of char written     : %llu\n", statp[i].writech);
      }
}

이 프로그램은 다음과 비슷한 출력을 냅니다.

text
Statistics for CPU : cpu0
------------------
CPU user time (raw ticks)  : 2585
CPU sys  time (raw ticks)  : 25994
CPU idle time (raw ticks)  : 7688458
CPU wait time (raw ticks)  : 3207
number of syscalls         : 6051122
number of readings         : 436595
number of writings         : 1284469
number of forks            : 4804
number of execs            : 5420
number of char read        : 1014077004
number of char written     : 56464273
Statistics for CPU : cpu1
------------------
CPU user time (raw ticks)  : 23
CPU sys  time (raw ticks)  : 794
CPU idle time (raw ticks)  : 7703901
CPU wait time (raw ticks)  : 42
number of syscalls         : 66064
number of readings         : 3432
number of writings         : 20620
number of forks            : 412
number of execs            : 51
number of char read        : 7068025
number of char written     : 217425
Statistics for CPU : cpu2
------------------
CPU user time (raw ticks)  : 0
CPU sys  time (raw ticks)  : 720
CPU idle time (raw ticks)  : 7704041
CPU wait time (raw ticks)  : 0
number of syscalls         : 0
number of readings         : 0
number of writings         : 0
number of forks            : 0
number of execs            : 0
number of char read        : 0
number of char written     : 0
Statistics for CPU : cpu3
------------------
CPU user time (raw ticks)  : 0
CPU sys  time (raw ticks)  : 810
CPU idle time (raw ticks)  : 7703950
CPU wait time (raw ticks)  : 0
number of syscalls         : 0
number of readings         : 0
number of writings         : 0
number of forks            : 0
number of execs            : 0
number of char read        : 0
number of char written     : 0
Statistics for CPU : cpu4
------------------
CPU user time (raw ticks)  : 243
CPU sys  time (raw ticks)  : 1799
CPU idle time (raw ticks)  : 7702802
CPU wait time (raw ticks)  : 62
number of syscalls         : 722482
number of readings         : 34416
number of writings         : 2994
number of forks            : 597
number of execs            : 453
number of char read        : 128511349
number of char written     : 2352602
Statistics for CPU : cpu5
------------------
CPU user time (raw ticks)  : 0
CPU sys  time (raw ticks)  : 209834
CPU idle time (raw ticks)  : 7676489
CPU wait time (raw ticks)  : 0
number of syscalls         : 729
number of readings         : 42
number of writings         : 0
number of forks            : 16
number of execs            : 1
number of char read        : 14607
number of char written     : 0
Statistics for CPU : cpu6
------------------
CPU user time (raw ticks)  : 0
CPU sys  time (raw ticks)  : 210391
CPU idle time (raw ticks)  : 7677505
CPU wait time (raw ticks)  : 0
number of syscalls         : 0
number of readings         : 0
number of writings         : 0
number of forks            : 0
number of execs            : 0
number of char read        : 0
number of char written     : 0
Statistics for CPU : cpu7
------------------
CPU user time (raw ticks)  : 0
CPU sys  time (raw ticks)  : 209884
CPU idle time (raw ticks)  : 7675736
CPU wait time (raw ticks)  : 0
number of syscalls         : 0
number of readings         : 0
number of writings         : 0
number of forks            : 0
number of execs            : 0
number of char read        : 0
number of char written     : 0

동적 논리 파티션(DLPAR)을 쓰는 환경에서는 쓸 수 있는 perfstat_cpu_t 구조체 수가 perfstat_cpu_total_t의 ncpus_high 필드와 같습니다. 이 수는 마지막 재부팅 이후 활성이었던 프로세서의 가장 큰 색인입니다. 프로세서가 오프라인이 되거나 다른 파티션으로 옮겨져도 그 프로세서의 성능 지표를 담은 커널 데이터 구조는 해제되지 않고 정보 갱신만 멈춥니다. perfstat_cpu_total_t 구조체의 ncpus 필드는 활성 프로세서 수이지만 perfstat_cpu 인터페이스는 ncpus_high개의 구조체를 돌려줍니다.

응용 프로그램은 클록 틱 증가량으로 오프라인이거나 옮겨진 프로세서를 알아낼 수 있습니다. 두 번의 perfstat_cpu 호출 사이에 어떤 프로세서의 user, sys, idle, wait 필드 합이 같으면, 그 프로세서는 구간 내내 오프라인이었습니다. 그 합에 10ms(클록 틱 하나의 값)를 곱한 값이 시간 간격과 맞지 않으면, 그 프로세서는 구간 내내 온라인이었던 것이 아닙니다.

위 프로그램은 mpstat의 동작을 흉내 내며 perfstat_cpu를 쓰는 방법을 보여 줍니다.

영어 원문

perfstat_cpu interface

The perfstat_cpu interface returns a set of structures of type perfstat_cpu_t, which is defined in the libperfstat.h file.

Selected fields from the perfstat_cpu_t structure include:

  • name — Logical processor name (cpu0, cpu1, ...)
  • user — Number of clock ticks spent in user mode
  • sys — Number of clock ticks spent in system (kernel) mode
  • idle — Number of clock ticks spent idle with no I/O pending
  • wait — Number of clock ticks spent idle with I/O pending
  • syscall — Number of system call executed

Several other CPU-related metrics (such as number of forks, read, write, and execs) are also returned. For a complete list, see the perfstat_cpu_t section in the libperfstat.h header.

The following code shows an example of how the perfstat_cpu interface is used:

(48줄짜리 예는 위 한글 본문에 그대로 실었습니다.)

The program displays an output that is similar to the following example output:

(104줄짜리 예는 위 한글 본문에 그대로 실었습니다.)

In an environment where dynamic logical partitioning is used, the number of perfstat_cpu_t structures available is equal to the ncpus_high field in the perfstat_cpu_total_t. This number represents the highest index of any active processor since the last reboot. Kernel data structures holding performance metrics for processors are not deallocated when processors are turned offline or moved to a different partition and it stops updating the information. The CPUs field of the perfstat_cpu_total_t structure represents the number of active processors, but the perfstat_cpu interface returns ncpus_high structures.

Applications can detect offline or moved processors by checking clock-tick increments. If the sum of the user, sys, idle, and wait fields is identical for a given processor between two perfstat_cpu calls, that processor has been offline for the complete interval. If the sum multiplied by 10 ms (the value of a clock tick) does not match the time interval, the processor has not been online for the complete interval.

The preceding program emulates mpstat behavior and also shows how perfstat_cpu is used.

(6.1) perfstat_cpu_util 인터페이스

perfstat_cpu_util 인터페이스는 libperfstat.h 파일에 정의된 perfstat_cpu_util_t 구조체 묶음을 돌려줍니다.

perfstat_cpu_util 인터페이스의 필드는 다음과 같습니다.

필드 설명
cpu_id CPU ID
entitlement 파티션의 권리(entitlement) 용량
user_pct 사용자 모드 사용률(%)
kern_pct 커널 모드 사용률(%)
idle_pct 유휴 모드 사용률(%)
wait_pct 대기 모드 사용률(%)
physical_busy 물리 CPU가 바쁜 정도
physical_consumed 파티션이 쓴 전체 CPU
freq_pct 마지막 구간의 평균 주파수(%)
entitlement_pct 권리 용량 가운데 쓴 비율(%)
busy_pct 권리 용량 가운데 바쁜 비율(%)
idle_donated_pct 기증한(donated) 유휴 사이클의 비율(%)
busy_donated_pct 기증한 바쁜 사이클의 비율(%)
idle_stolen_pct 빼앗긴(stolen) 유휴 사이클의 비율(%)
busy_stolen_pct 빼앗긴 바쁜 사이클의 비율(%)
float l_user_pct 논리 프로세서 틱 기준 사용자 모드 사용률(%)
float l_kern_pct 논리 프로세서 틱 기준 커널 모드 사용률(%)
float l_idle_pct 논리 프로세서 틱 기준 유휴 모드 사용률(%)
float l_wait_pct 논리 프로세서 틱 기준 대기 모드 사용률(%)
u_longlong_t delta_time 사용률을 계산한 구간의 길이(ms)

perfstat_rawdata_t 데이터 구조의 type 필드를 UTIL_CPU_TOTAL이나 UTIL_CPU로 주면 perfstat_cpu_util로 각각 시스템 사용률과 CPU별 사용률을 얻을 수 있습니다. UTIL_CPU_TOTAL과 UTIL_CPU는 perfstat_rawdata_t 데이터 구조의 정의에서 볼 수 있는 매크로입니다.

시스템 수준 사용률을 구하는 perfstat_cpu_util API 사용 예입니다.

text
#include <libperfstat.h>
#define PERIOD 5
void main()
{
   perfstat_cpu_total_t *newt, *oldt;
   perfstat_cpu_util_t *util;
   perfstat_rawdata_t data;
   int rc;
   oldt = (perfstat_cpu_total_t*)malloc(sizeof(perfstat_cpu_total_t)*1);
   if(oldt==NULL){
      perror ("malloc");
      exit(-1);
   }
   newt = (perfstat_cpu_total_t*)malloc(sizeof(perfstat_cpu_total_t)*1);
   if(newt==NULL){
      perror ("malloc");
      exit(-1);
   }
   util = (perfstat_cpu_util_t*)malloc(sizeof(perfstat_cpu_util_t)*1);
   if(util==NULL){
      perror ("malloc");
      exit(-1);
   }
   rc = perfstat_cpu_total(NULL, oldt, sizeof(perfstat_cpu_total_t), 1);
    if(rc <= 0)
    {
    perror("Error in perfstat_cpu_total");
       exit(-1);
    }
   sleep(PERIOD);
     rc = perfstat_cpu_total(NULL, newt, sizeof(perfstat_cpu_total_t), 1);
     if(rc <= 0)
     {
      perror("Error in perfstat_cpu_total");
       exit(-1);
     }
    data.type = UTIL_CPU_TOTAL;
    data.curstat = newt; data.prevstat= oldt;
    data.sizeof_data = sizeof(perfstat_cpu_total_t);
    data.cur_elems = 1;
    data.prev_elems = 1;
    rc = perfstat_cpu_util(&data, util,sizeof(perfstat_cpu_util_t), 1);
 if(rc <= 0)
    {
      perror("Error in perfstat_cpu_util");
      exit(-1);
    }
   printf("=======Overall CPU Utilization Metrics=======\n");
   printf("Utilization Metrics for a period of %d seconds\n",PERIOD);
   printf("User Percentage =                %f\n",util->user_pct);
   printf("System Percentage =              %f\n",util->kern_pct);
   printf("Idle Percentage =                %f\n",util->idle_pct);
   printf("Wait Percentage =                %f\n",util->wait_pct);
   printf("Physical Busy =                  %f\n",util->physical_busy);
   printf("Physical Consumed =              %f\n",util->physical_consumed);
   printf("Freq Percentage =                %f\n",util->freq_pct);
   printf("Entitlement Used Percentage =    %f\n",util->entitlement_pct);
   printf("Entitlement Busy Percentage =    %f\n",util->busy_pct);
   printf("Idle Cycles Donated Percentage = %f\n",util->idle_donated_pct);
   printf("Busy Cycles Donated Percentage = %f\n",util->busy_donated_pct);
   printf("Idle Cycles Stolen Percentage =  %f\n",util->idle_stolen_pct);
   printf("Busy Cycles Stolen Percentage =  %f\n",util->busy_stolen_pct);
   printf("User percentage for logical cpu in ticks = %f\n",util->l_user_pct);
   printf("Sytem percentage for logical cpu in ticks= %f\n",util->l_kern_pct);
   printf("Idle percentage for logical cpu in ticks=  %f\n",util->l_idle_pct);
   printf("Wait percentage for logical cpu in ticks=  %f\n",util->l_wait_pct);
   printf("delta time in milliseconds =  %llu \n",util->delta_time);
   printf("=============================================\n");
}

이 프로그램은 다음과 비슷한 출력을 냅니다.

text
=======Overall CPU Utilization Metrics=======
Utilization Metrics for a period of 5 seconds
User Percentage =                0.050689
System Percentage =              0.262137
Idle Percentage =                99.687172
Wait Percentage =                0.000000
Physical Busy =                  0.003128
Physical Consumed =              0.008690
Freq Percentage =                99.935417
Entitlement Used Percentage =    0.869017
Entitlement Busy Percentage =    0.312826
Idle Cycles Donated Percentage = 0.000000
Busy Cycles Donated Percentage = 0.000000
Idle Cycles Stolen Percentage =  0.000000
Busy Cycles Stolen Percentage =  0.000000
User percentage for logical cpu in ticks = 0.000000
Sytem percentage for logical cpu in ticks= 0.082034
Idle percentage for logical cpu in ticks=  99.917969
Wait percentage for logical cpu in ticks=  0.000000
delta time in milliseconds =  4980

perfstat_cpu_util 인터페이스로 CPU별 시스템 사용률과 CPU 사용률을 계산하는 예입니다.

text
#include <libperfstat.h>
#define PERIOD 5
void main()
{
  perfstat_rawdata_t data;
  perfstat_cpu_util_t *util;
  perfstat_cpu_t *newt,*oldt;
  perfstat_id_t id;
  int i,cpu_count,rc;
  /* Check how many perfstat_cpu_t structures are available */
  cpu_count = perfstat_cpu(NULL, NULL,sizeof(perfstat_cpu_t),0);
  /* check for error */
  if(cpu_count <= 0)
   {
     perror("Error in perfstat_cpu");
     exit(-1);
   }
    /* allocate enough memory */
   oldt = (perfstat_cpu_t *)calloc(cpu_count,sizeof(perfstat_cpu_t));
   if(oldt == NULL)
   {
     perror("Memory Allocation Error");
     exit(-1);
   }
   /* set name to first cpu */
   strcpy(id.name,FIRST_CPU);
   /* ask to get all the structures available in one call */
   rc = perfstat_cpu(&id, oldt, sizeof(perfstat_cpu_t), cpu_count);
    /* check for error */
   if(rc <=0)
   {
     perror("Error in perfstat_cpu");
      exit(-1);
    }
    data.type = UTIL_CPU;
    data.prevstat= oldt;
    data.sizeof_data = sizeof(perfstat_cpu_t);
    data.prev_elems = cpu_count;
    sleep(PERIOD);
     /* Check how many perfstat_cpu_t structures are available after a defined period */
   cpu_count = perfstat_cpu(NULL, NULL,sizeof(perfstat_cpu_t),0);
 /* Check for error */
    if(cpu_count <= 0)
    {
     perror("Error in perfstat_cpu");
      exit(-1);
    }
    data.cur_elems = cpu_count;
     if(data.prev_elems != data.cur_elems)
    {
     perror("The number of CPUs has become different for defined period");
     exit(-1);
    }
  /* allocate enough memory */
  newt = (perfstat_cpu_t *)calloc(cpu_count,sizeof(perfstat_cpu_t));
  util = (perfstat_cpu_util_t *)calloc(cpu_count,sizeof(perfstat_cpu_util_t));
  if(newt == NULL || util == NULL)
  {
   perror("Memory Allocation Error");
   exit(-1);
  }
  data.curstat = newt;
  rc = perfstat_cpu(&id, newt, sizeof(perfstat_cpu_t), cpu_count);
   if(rc <= 0)
   {
     perror("Error in perfstat_cpu");
     exit(-1);
   }
    /* Calculate CPU Utilization Metrics*/
   rc = perfstat_cpu_util(&data, util, sizeof(perfstat_cpu_util_t), cpu_count);
if(rc <= 0)
  {
    perror("Error in perfstat_cpu_util");
    exit(-1);
  }
printf("========= Per CPU Utilization Metrics =========\n");
  printf("Utilization Metrics for a period of %d seconds\n",PERIOD);
  printf("===============================================\n");
  for ( i = 0;i<cpu_count;i++)
{
   printf("Utilization metrics for CPU-ID =    %s\n",util[i].cpu_id);
   printf("User Percentage =                   %f\n",util[i].user_pct);
   printf("System Percentage =                 %f\n",util[i].kern_pct);
printf("Idle Percentage =                   %f\n",util[i].idle_pct);
   printf("Wait Percentage =                   %f\n",util[i].wait_pct);
   printf("Physical Busy =                     %f\n",util[i].physical_busy);
   printf("Physical Consumed =                 %f\n",util[i].physical_consumed);
   printf("Freq Percentage =                   %f\n",util[i].freq_pct);
   printf("Entitlement Used Percentage =       %f\n",util[i].entitlement_pct);
   printf("Entitlement Busy Percentage =       %f\n",util[i].busy_pct);
   printf("Idle Cycles Donated Percentage =    %f\n",util[i].idle_donated_pct);
   printf("Busy Cycles Donated Percentage =    %f\n",util[i].busy_donated_pct);
   printf("Idle Cycles Stolen Percentage =     %f\n",util[i].idle_stolen_pct);
   printf("Busy Cycles Stolen Percentage =     %f\n",util[i].busy_stolen_pct);
   printf("system percentage for logical cpu in ticks = %f\n",util[i].l_kern_pct);
   printf("idle percentage for logical cpu in ticks =  %f\n",util[i].l_idle_pct);
   printf("wait percentage for logical cpu in ticks =  %f\n",util[i].l_wait_pct);
   printf("delta time in milliseconds =  %llu \n",util[i].delta_time);
   printf("\n\n");
}
   printf("===========================================\n");
}

이 프로그램은 다음과 비슷한 출력을 냅니다.

text
========= Per CPU Utilization Metrics =========
Utilization Metrics for a period of 5 seconds
===============================================
Utilization metrics for CPU-ID =    cpu0
User Percentage =                   14.850358
System Percentage =                 63.440376
Idle Percentage =                   21.709267
Wait Percentage =                   0.000000
Physical Busy =                     0.003085
Physical Consumed =                 0.003941
Freq Percentage =                   99.975967
Entitlement Used Percentage =       0.394055
Entitlement Busy Percentage =       0.308508
Idle Cycles Donated Percentage =    0.000000
Busy Cycles Donated Percentage =    0.000000
Idle Cycles Stolen Percentage =     0.000000
Busy Cycles Stolen Percentage =     0.000000
system percentage for logical cpu in ticks = 0.000000
idle percentage for logical cpu in ticks =  100.000000
wait percentage for logical cpu in ticks =  0.000000
delta time in milliseconds =  4999
Utilization metrics for CPU-ID =    cpu1
User Percentage =                   0.000000
System Percentage =                 4.720662
Idle Percentage =                   95.279335
Wait Percentage =                   0.000000
Physical Busy =                     0.000065
Physical Consumed =                 0.001371
Freq Percentage =                   99.938919
Entitlement Used Percentage =       0.137110
Entitlement Busy Percentage =       0.006472
Idle Cycles Donated Percentage =    0.000000
Busy Cycles Donated Percentage =    0.000000
Idle Cycles Stolen Percentage =     0.000000
Busy Cycles Stolen Percentage =     0.000000
system percentage for logical cpu in ticks = 0.000000
idle percentage for logical cpu in ticks =  100.000000
wait percentage for logical cpu in ticks =  0.000000
delta time in milliseconds =  5000
Utilization metrics for CPU-ID =    cpu2
User Percentage =                   0.000000
System Percentage =                 5.848962
Idle Percentage =                   94.151039
Wait Percentage =                   0.000000
Physical Busy =                     0.000079
Physical Consumed =                 0.001348
Freq Percentage =                   99.900566
Entitlement Used Percentage =       0.134820
Entitlement Busy Percentage =       0.007886
Idle Cycles Donated Percentage =    0.000000
Busy Cycles Donated Percentage =    0.000000
Idle Cycles Stolen Percentage =     0.000000
Busy Cycles Stolen Percentage =     0.000000
system percentage for logical cpu in ticks = 0.000000
idle percentage for logical cpu in ticks =  100.000000
wait percentage for logical cpu in ticks =  0.000000
delta time in milliseconds =  5000
Utilization metrics for CPU-ID =    cpu3
User Percentage =                   0.000000
System Percentage =                 4.644570
Idle Percentage =                   95.355431
Wait Percentage =                   0.000000
Physical Busy =                     0.000061
Physical Consumed =                 0.001312
Freq Percentage =                   99.925430
Entitlement Used Percentage =       0.131174
Entitlement Busy Percentage =       0.006092
Idle Cycles Donated Percentage =    0.000000
Busy Cycles Donated Percentage =    0.000000
Idle Cycles Stolen Percentage =     0.000000
Busy Cycles Stolen Percentage =     0.000000
system percentage for logical cpu in ticks = 0.000000
idle percentage for logical cpu in ticks =  100.000000
wait percentage for logical cpu in ticks =  0.000000
delta time in milliseconds =  5000
Utilization metrics for CPU-ID =    cpu4
User Percentage =                   0.000000
System Percentage =                 55.325123
Idle Percentage =                   44.674877
Wait Percentage =                   0.000000
Physical Busy =                     0.000153
Physical Consumed =                 0.000276
Freq Percentage =                   99.927551
Entitlement Used Percentage =       0.027605
Entitlement Busy Percentage =       0.015273
Idle Cycles Donated Percentage =    0.000000
Busy Cycles Donated Percentage =    0.000000
Idle Cycles Stolen Percentage =     0.000000
Busy Cycles Stolen Percentage =     0.000000
system percentage for logical cpu in ticks = 0.000000
idle percentage for logical cpu in ticks =  100.000000
wait percentage for logical cpu in ticks =  0.000000
delta time in milliseconds =  4999
Utilization metrics for CPU-ID =    cpu5
User Percentage =                   0.000000
System Percentage =                 1.854463
Idle Percentage =                   98.145538
Wait Percentage =                   0.000000
Physical Busy =                     0.000002
Physical Consumed =                 0.000113
Freq Percentage =                   99.612183
Entitlement Used Percentage =       0.011326
Entitlement Busy Percentage =       0.000210
Idle Cycles Donated Percentage =    0.000000
Busy Cycles Donated Percentage =    0.000000
Idle Cycles Stolen Percentage =     0.000000
Busy Cycles Stolen Percentage =     0.000000
system percentage for logical cpu in ticks = 0.255102
idle percentage for logical cpu in ticks =  99.744896
wait percentage for logical cpu in ticks =  0.000000
delta time in milliseconds =  3913
Utilization metrics for CPU-ID =    cpu6
User Percentage =                   0.000000
System Percentage =                 1.776852
Idle Percentage =                   98.223145
Wait Percentage =                   0.000000
Physical Busy =                     0.000002
Physical Consumed =                 0.000115
Freq Percentage =                   99.475967
Entitlement Used Percentage =       0.011506
Entitlement Busy Percentage =       0.000204
Idle Cycles Donated Percentage =    0.000000
Busy Cycles Donated Percentage =    0.000000
Idle Cycles Stolen Percentage =     0.000000
Busy Cycles Stolen Percentage =     0.000000
system percentage for logical cpu in ticks = 0.255102
idle percentage for logical cpu in ticks =  99.744896
wait percentage for logical cpu in ticks =  0.000000
delta time in milliseconds =  3912
Utilization metrics for CPU-ID =    cpu7
User Percentage =                   0.000000
System Percentage =                 2.138275
Idle Percentage =                   97.861725
Wait Percentage =                   0.000000
Physical Busy =                     0.000002
Physical Consumed =                 0.000112
Freq Percentage =                   99.593727
Entitlement Used Percentage =       0.011205
Entitlement Busy Percentage =       0.000240
Idle Cycles Donated Percentage =    0.000000
Busy Cycles Donated Percentage =    0.000000
Idle Cycles Stolen Percentage =     0.000000
Busy Cycles Stolen Percentage =     0.000000
system percentage for logical cpu in ticks = 0.255102
idle percentage for logical cpu in ticks =  99.744896
wait percentage for logical cpu in ticks =  0.000000
delta time in milliseconds =  3912

simplelparstat.c 코드 예

simplelparstat.c 코드를 쓰는 예입니다.

text
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <libperfstat.h>
#include <sys/systemcfg.h>
#define XINTFRAC ((double)(_system_configuration.Xint)/(double)(_system_configuration.Xfrac))
/* convert physical processor tics to seconds */
#define HTIC2SEC(x) ((double)x * XINTFRAC)/(double)1000000000.0
#define INTERVAL_DEFAULT   2
#define COUNT_DEFAULT    10
/*simplelparstat.c file can be used in two modes:-
1) Auto Mode:It makes use of perfstat_cpu_util API to calculate utilization values,enable ’UTIL_AUTO’ macro for execution in auto mode.
2) Manual Mode: Calculations are done in the current code.
*/
/*#define UTIL_AUTO     1*/
#ifdef  UTIL_AUTO
 #define UTIL_MS 1
 #define UTIL_PCT 0
 #define UTIL_CORE 2
 #define UTIL_PURR 0
 #define UTIL_SPURR 1
 void display_lpar_util_auto(int mode,int cpumode,int count,int interval);
#endif
static int disp_util_header = 1;
static u_longlong_t last_time_base;
static u_longlong_t last_pcpu_user, last_pcpu_sys, last_pcpu_idle, last_pcpu_wait;
static u_longlong_t last_lcpu_user, last_lcpu_sys, last_lcpu_idle, last_lcpu_wait;
static u_longlong_t last_busy_donated, last_idle_donated;
static u_longlong_t last_busy_stolen, last_idle_stolen;
static u_longlong_t last_phint = 0, last_vcsw = 0, last_pit = 0;
/* support for remote node statistics collection in a cluster environment */
perfstat_id_node_t nodeid;
static char nodename[MAXHOSTNAMELEN] = "";
static int collect_remote_node_stats = 0;
void display_lpar_util(void);
int main(int argc, char* argv[])
{
    int interval = INTERVAL_DEFAULT;
    int count = COUNT_DEFAULT;
    int i, rc;
    char *optlist = "i:c:n:";
    int mode=0,cpumode=0;
    /* Process the arguments */
    while ((i = getopt(argc, argv, optlist)) != EOF)
    {
        switch(i)
        {
            case ’i’:               /* Interval */
                     interval = atoi(optarg);
                     if( interval <= 0 )
                         interval = INTERVAL_DEFAULT;
                     break;
            case ’c’:               /* Number of interations */
                     count = atoi(optarg);
                     if( count <= 0 )
                         count = COUNT_DEFAULT;
                     break;
            case ’n’:               /* Node name in a cluster environment */
                     strncpy(nodename, optarg, MAXHOSTNAMELEN);
                     nodename[MAXHOSTNAMELEN-1] = ’\0’;
                     collect_remote_node_stats = 1;
                     break;
            default:
                    /* Invalid arguments. Print the usage and terminate */
                    fprintf (stderr, "usage: %s [-i <interval in seconds> ] [-c <number of iterations> ] [-n <node name in the cluster> ]\n", argv[0]);
                    return(-1);
        }
    }
    if(collect_remote_node_stats)
    {   /* perfstat_config needs to be called to enable cluster statistics collection */
        rc = perfstat_config(PERFSTAT_ENABLE|PERFSTAT_CLUSTER_STATS, NULL);
        if (rc == -1)
        {
            perror("cluster statistics collection is not available");
            exit(-1);
        }
    }
    #ifdef UTIL_AUTO
      printf("Enter CPU mode.\n");
      printf(" 0 PURR \n 1 SPURR \n");
      scanf("%d",&cpumode);
      printf("Enter print mode.\n");
      printf(" 0 PERCENTAGE\n 1 MILLISECONDS\n 2 CORES \n");
      scanf("%d",&mode);
      if((mode>2)&& (cpumode>1))
      {
        printf("Error: Invalid Input\n");
        exit(0);
      }
      display_lpar_util_auto(mode,cpumode,count,interval);
    #else
    /* Iterate "count" times */
    while (count > 0)
    {
        display_lpar_util();
        sleep(interval);
        count--;
    }
    #endif
    if(collect_remote_node_stats)
    {   /* Now disable cluster statistics by calling perfstat_config */
        perfstat_config(PERFSTAT_DISABLE|PERFSTAT_CLUSTER_STATS, NULL);
    }
    return(0);
}
/* Save the current values for the next iteration */
void save_last_values(perfstat_cpu_total_t *cpustats, perfstat_partition_total_t *lparstats)
{
    last_vcsw      = lparstats->vol_virt_cswitch + lparstats->invol_virt_cswitch;
    last_time_base = lparstats->timebase_last;
    last_phint     = lparstats->phantintrs;
    last_pit       = lparstats->pool_idle_time;
    last_pcpu_user = lparstats->puser;
    last_pcpu_sys  = lparstats->psys;
    last_pcpu_idle = lparstats->pidle;
    last_pcpu_wait = lparstats->pwait;
    last_lcpu_user = cpustats->user;
    last_lcpu_sys  = cpustats->sys;
    last_lcpu_idle = cpustats->idle;
    last_lcpu_wait = cpustats->wait;
    last_busy_donated = lparstats->busy_donated_purr;
    last_idle_donated = lparstats->idle_donated_purr;
    last_busy_stolen = lparstats->busy_stolen_purr;
    last_idle_stolen = lparstats->idle_stolen_purr;
}
/* retrieve metrics using perfstat API */
void collect_metrics (perfstat_cpu_total_t *cpustats, perfstat_partition_total_t *lparstats)
{
    if (collect_remote_node_stats)
    {
        strncpy(nodeid.u.nodename, nodename, MAXHOSTNAMELEN);
        nodeid.spec = NODENAME;
        if (perfstat_partition_total_node(&nodeid, lparstats, sizeof(perfstat_partition_total_t), 1) <= 0) {
            perror("perfstat_partition_total_node");
            exit(-1);
        }
        if (perfstat_cpu_total_node(&nodeid, cpustats, sizeof(perfstat_cpu_total_t), 1) <= 0) {
            perror("perfstat_cpu_total_node");
            exit(-1);
        }
    }
    else
    {
        if (perfstat_partition_total(NULL, lparstats, sizeof(perfstat_partition_total_t), 1) <= 0) {
            perror("perfstat_partition_total");
            exit(-1);
        }
        if (perfstat_cpu_total(NULL, cpustats, sizeof(perfstat_cpu_total_t), 1) <= 0) {
            perror("perfstat_cpu_total");
            exit(-1);
        }
    }
}
/* print header informations */
void print_header(perfstat_partition_total_t *lparstats)
{
    if (lparstats->type.b.shared_enabled) { /* partition is a SPLPAR */
       if (lparstats->type.b.pool_util_authority) { /* partition has PUA access */
          printf("\n%5s %5s %6s %6s %5s %5s %5s %5s %4s %5s",
          "%user", "%sys", "%wait", "%idle", "physc", "%entc", "lbusy", "app", "vcsw", "phint");
          printf("\n%5s %5s %6s %6s %5s %5s %5s %5s %4s %5s",
          "-----", "----", "-----", "-----", "-----", "-----", "-----", "---", "----", "-----");
       } else {
          printf("\n%5s %5s %6s %6s %5s %5s %5s %4s %5s",
          "%user", "%sys", "%wait", "%idle", "physc", "%entc", "lbusy", "vcsw", "phint");
          printf("\n%5s %5s %6s %6s %5s %5s %5s %4s %5s",
          "-----", "----", "-----", "-----", "-----", "-----", "-----", "----", "-----");
       }
    } else { /* partition is a DLPAR */
       printf("\n%5s %5s %6s %6s", "%user", "%sys", "%wait", "%idle");
       printf("\n%5s %5s %6s %6s", "-----", "----", "-----", "-----");
       if (lparstats->type.b.donate_enabled) { /* if donation is enabled for this DLPAR */
         printf(" %6s %6s", "%phsyc", "%vcsw");
         printf(" %6s %6s", "------", "-----");
       }
    }
    fprintf(stdout,"\n");
}
/* Gather and display lpar utilization metrics */
void display_lpar_util(void)
{
    u_longlong_t delta_pcpu_user, delta_pcpu_sys, delta_pcpu_idle, delta_pcpu_wait;
    u_longlong_t delta_lcpu_user, delta_lcpu_sys, delta_lcpu_idle, delta_lcpu_wait;
    u_longlong_t delta_busy_stolen, delta_busy_donated, delta_idle_stolen, delta_idle_donated;
    u_longlong_t vcsw, lcputime, pcputime;
    u_longlong_t entitled_purr, unused_purr;
    u_longlong_t delta_purr, delta_time_base;
    double phys_proc_consumed, entitlement, percent_ent, delta_sec;
    perfstat_partition_total_t lparstats;
    perfstat_cpu_total_t cpustats;
    /* retrieve the metrics */
    collect_metrics (&cpustats, &lparstats);
    /* Print the header for utilization metrics (only once) */
    if (disp_util_header) {
       print_header (&lparstats);
       disp_util_header = 0;
       /* first iteration, we only read the data, print the header and save the data */
       save_last_values(&cpustats, &lparstats);
       return;
    }
    /* calculate physcial processor tics during the last interval in user, system, idle and wait mode  */
    delta_pcpu_user  = lparstats.puser - last_pcpu_user;
    delta_pcpu_sys   = lparstats.psys  - last_pcpu_sys;
    delta_pcpu_idle  = lparstats.pidle - last_pcpu_idle;
    delta_pcpu_wait  = lparstats.pwait - last_pcpu_wait;
    /* calculate total physcial processor tics during the last interval */
    delta_purr = pcputime = delta_pcpu_user + delta_pcpu_sys + delta_pcpu_idle + delta_pcpu_wait;
    /* calculate clock tics during the last interval in user, system, idle and wait mode */
    delta_lcpu_user  = cpustats.user - last_lcpu_user;
    delta_lcpu_sys   = cpustats.sys  - last_lcpu_sys;
    delta_lcpu_idle  = cpustats.idle - last_lcpu_idle;
    delta_lcpu_wait  = cpustats.wait - last_lcpu_wait;
    /* calculate total clock tics during the last interval */
    lcputime = delta_lcpu_user + delta_lcpu_sys + delta_lcpu_idle + delta_lcpu_wait;
    /* calculate entitlement for this partition - entitled physical processors for this partition */
    entitlement = (double)lparstats.entitled_proc_capacity / 100.0 ;
    /* calculate delta time in terms of physical processor tics */
    delta_time_base = lparstats.timebase_last - last_time_base;
    if (lparstats.type.b.shared_enabled) { /* partition is a SPLPAR */
        /* calculate entitled physical processor tics for this partitions */
        entitled_purr = delta_time_base * entitlement;
        if (entitled_purr < delta_purr) { /* for uncapped SPLPAR */
            /* in case of uncapped SPLPAR, consider entitled physical processor tics or
             * consumed physical processor tics, which ever is greater */
            entitled_purr = delta_purr;
        }
        /* calculate unused physical processor tics out of the entitled physical processor tics */
        unused_purr = entitled_purr - delta_purr;
        /* distributed unused physical processor tics amoung wait and idle proportionally to wait and idle in clock tics */
        delta_pcpu_wait += unused_purr * ((double)delta_lcpu_wait / (double)(delta_lcpu_wait + delta_lcpu_idle));
        delta_pcpu_idle += unused_purr * ((double)delta_lcpu_idle / (double)(delta_lcpu_wait + delta_lcpu_idle));
        /* far SPLPAR, consider the entitled physical processor tics as the actual delta physical processor tics */
        pcputime = entitled_purr;
    }
    else if (lparstats.type.b.donate_enabled) { /* if donation is enabled for this DLPAR */
        /* calculate busy stolen and idle stolen physical processor tics during the last interval */
        /* these physical processor tics are stolen from this partition by the hypervsior
         * which will be used by wanting partitions */
        delta_busy_stolen = lparstats.busy_stolen_purr - last_busy_stolen;
        delta_idle_stolen = lparstats.idle_stolen_purr - last_idle_stolen;
        /* calculate busy donated and idle donated physical processor tics during the last interval */
        /* these physical processor tics are voluntarily donated by this partition to the hypervsior
         * which will be used by wanting partitions */
        delta_busy_donated = lparstats.busy_donated_purr - last_busy_donated;
        delta_idle_donated = lparstats.idle_donated_purr - last_idle_donated;
        /* add busy donated and busy stolen to the kernel bucket, as cpu
         * cycles were donated / stolen when this partition is busy */
        delta_pcpu_sys += delta_busy_donated;
        delta_pcpu_sys += delta_busy_stolen;
        /* distribute idle stolen to wait and idle proportionally to the logical wait and idle in clock tics, as
         * cpu cycles were stolen when this partition is idle or in wait */
        delta_pcpu_wait += delta_idle_stolen *
                              ((double)delta_lcpu_wait / (double)(delta_lcpu_wait + delta_lcpu_idle));
        delta_pcpu_idle += delta_idle_stolen *
                              ((double)delta_lcpu_idle / (double)(delta_lcpu_wait + delta_lcpu_idle));
        /* distribute idle donated to wait and idle proportionally to the logical wait and idle in clock tics, as
         * cpu cycles were donated when this partition is idle or in wait */
        delta_pcpu_wait += delta_idle_donated *
                              ((double)delta_lcpu_wait / (double)(delta_lcpu_wait + delta_lcpu_idle));
        delta_pcpu_idle += delta_idle_donated *
                              ((double)delta_lcpu_idle / (double)(delta_lcpu_wait + delta_lcpu_idle));
        /* add donated to the total physical processor tics for CPU usage calculation, as they were
         * distributed to respective buckets accordingly */
        pcputime +=  (delta_idle_donated + delta_busy_donated);
        /* add stolen to the total physical processor tics for CPU usage calculation, as they were
         * distributed to respective buckets accordingly */
        pcputime +=  (delta_idle_stolen + delta_busy_stolen);
    }
    /* Processor Utilization - Applies for both SPLPAR and DLPAR*/
    printf("%5.1f ", (double)delta_pcpu_user * 100.0 / (double)pcputime);
    printf("%5.1f ", (double)delta_pcpu_sys  * 100.0 / (double)pcputime);
    printf("%6.1f ", (double)delta_pcpu_wait * 100.0 / (double)pcputime);
    printf("%6.1f ", (double)delta_pcpu_idle * 100.0 / (double)pcputime);
    if (lparstats.type.b.shared_enabled) { /* print SPLPAR specific stats */
        /* Physical Processor Consumed by this partition */
        phys_proc_consumed = (double)delta_purr / (double)delta_time_base;
        printf("%5.2f ", (double)phys_proc_consumed);
        /* Percentage of Entitlement Consumed - percentage of entitled physical processor tics consumed */
        percent_ent = (double)((phys_proc_consumed / entitlement) * 100);
        printf("%5.1f ", percent_ent);
        /* Logical Processor Utilization of this partition */
        printf("%5.1f ", (double)(delta_lcpu_user+delta_lcpu_sys) * 100.0 / (double)lcputime);
        if (lparstats.type.b.pool_util_authority) {
        /* Available physical Processor units available in the shared pool (app) */
           printf("%5.2f ", (double)(lparstats.pool_idle_time - last_pit) /
                 XINTFRAC*(double)delta_time_base);
        }
        /* Virtual CPU Context Switches per second */
        vcsw = lparstats.vol_virt_cswitch + lparstats.invol_virt_cswitch;
      delta_sec = HTIC2SEC(delta_time_base);
        printf("%4.0f ", (double)(vcsw - last_vcsw) / delta_sec);
        /* Phantom Interrupts per second */
        printf("%5.0f",(double)(lparstats.phantintrs - last_phint) / delta_sec);
    }
    else if (lparstats.type.b.donate_enabled) { /* print donation-enabled DLPAR specific stats */
        /* Physical Processor Consumed by this partition
         * (excluding donated and stolen physical processor tics). */
        phys_proc_consumed = (double)delta_purr / (double)delta_time_base;
        printf("%5.2f ", (double)phys_proc_consumed);
        /* Virtual CPU Context Switches per second */
        vcsw = lparstats.vol_virt_cswitch + lparstats.invol_virt_cswitch;
      delta_sec = HTIC2SEC(delta_time_base);
        printf("%5.0f ", (double)(vcsw - last_vcsw) / delta_sec);
    }
    printf("\n");
    save_last_values(&cpustats, &lparstats);
}
#ifdef UTIL_AUTO
void display_lpar_util_auto(int mode,int cpumode,int count,int interval)
{
    float user_core_purr,kern_core_purr,wait_core_purr,idle_core_purr;
    float user_core_spurr,kern_core_spurr,wait_core_spurr,idle_core_spurr,sum_core_spurr;
    u_longlong_t user_ms_purr,kern_ms_purr,wait_ms_purr,idle_ms_purr,sum_ms;
    u_longlong_t user_ms_spurr,kern_ms_spurr,wait_ms_spurr,idle_ms_spurr;
    perfstat_rawdata_t data;
    u_longlong_t delta_purr, delta_time_base;
    double phys_proc_consumed, entitlement, percent_ent, delta_sec;
    perfstat_partition_total_t lparstats;
    static perfstat_cpu_total_t oldt,newt;
    perfstat_cpu_util_t util;
    int rc;
    /* retrieve the metrics */
    /* Print the header for utilization metrics (only once) */
    if (disp_util_header) {
    if(mode==UTIL_PCT)
          printf("\n%5s %5s %6s %6s %5s  \n",
          "%user", "%sys", "%wait", "%idle", "physc");
    else if(mode==UTIL_MS)
          printf("\n%5s   %5s   %6s   %6s   %5s \n",
          "user(ms)", "sys(ms)", "wait(ms)", "idle(ms)", "physc");
    else if(mode==UTIL_CORE)
          printf("\n%5s  %5s  %6s  %6s  %5s  \n",
          "user", "sys", "wait", "idle", "physc");
       disp_util_header = 0;
       /* first iteration, we only read the data, print the header and save the data */
    }
  while(count)
  {
    collect_metrics (&oldt, &lparstats);
    sleep(interval);
    collect_metrics (&newt, &lparstats);
   data.type = UTIL_CPU_TOTAL;
   data.curstat = &newt; data.prevstat= &oldt;
   data.sizeof_data = sizeof(perfstat_cpu_total_t);
   data.cur_elems = 1;
   data.prev_elems = 1;
   rc = perfstat_cpu_util(&data, &util,sizeof(perfstat_cpu_util_t), 1);
   if(rc <= 0)
   {
     perror("Error in perfstat_cpu_util");
     exit(-1);
   }
   delta_time_base =  util.delta_time;
  switch(mode)
   {
   case  UTIL_PCT:
         printf(" %5.1f  %5.1f  %5.1f  %5.1f  %5.4f \n",util.user_pct,util.kern_pct,util.wait_pct,util.idle_pct,util.physical_consumed);
         break;
   case  UTIL_MS:
         user_ms_purr=((util.user_pct*delta_time_base)/100.0);
         kern_ms_purr=((util.kern_pct*delta_time_base)/100.0);
         wait_ms_purr=((util.wait_pct*delta_time_base)/100.0);
         idle_ms_purr=((util.idle_pct*delta_time_base)/100.0);
        if(cpumode==UTIL_PURR)
        {
            printf(" %llu    %llu    %llu    %llu   %5.4f\n",user_ms_purr,kern_ms_purr,wait_ms_purr,idle_ms_purr,util.physical_consumed);
        }
       else if(cpumode==UTIL_SPURR)
       {
            user_ms_spurr=(user_ms_purr*util.freq_pct)/100.0;
            kern_ms_spurr=(kern_ms_purr*util.freq_pct)/100.0;
            wait_ms_spurr=(wait_ms_purr*util.freq_pct)/100.0;
            sum_ms=user_ms_spurr+kern_ms_spurr+wait_ms_spurr;
            idle_ms_spurr=delta_time_base-sum_ms;
            printf(" %llu    %llu    %llu    %llu    %5.4f \n",user_ms_spurr,kern_ms_spurr,wait_ms_spurr,idle_ms_spurr,util.physical_consumed);
       }
            break;
   case  UTIL_CORE:
           user_core_purr=((util.user_pct*util.physical_consumed)/100.0);
           kern_core_purr=((util.kern_pct*util.physical_consumed)/100.0);
           wait_core_purr=((util.wait_pct*util.physical_consumed)/100.0);
           idle_core_purr=((util.idle_pct*util.physical_consumed)/100.0);
           user_core_spurr=((user_core_purr*util.freq_pct)/100.0);
           kern_core_spurr=((kern_core_purr*util.freq_pct)/100.0);
           wait_core_spurr=((wait_core_purr*util.freq_pct)/100.0);
           if(cpumode==UTIL_PURR)
           {
            printf("%5.4f   %5.4f   %5.4f   %5.4f   %5.4f\n",user_core_purr,kern_core_purr,wait_core_purr,idle_core_purr,util.physical_consumed);
           }
           else if(cpumode==UTIL_SPURR)
           {
           sum_core_spurr=user_core_spurr+kern_core_spurr+wait_core_spurr;
           idle_core_spurr=util.physical_consumed-sum_core_spurr;
            printf("%5.4f   %5.4f   %5.4f   %5.4f   %5.4f \n",user_core_spurr,kern_core_spurr,wait_core_spurr,idle_core_spurr,util.physical_consumed);
           }
           break;
           default:
           printf("In correct usage\n");
           return;
}
count--;
}
}
#endif

이 프로그램은 다음과 비슷한 출력을 냅니다.

text
%user  %sys  %wait  %idle physc %entc lbusy vcsw phint
-----  ----  -----  ----- ----- ----- ----- ---- -----
  0.1   0.3    0.0   99.6  0.01   1.1   0.2  285     0
  0.0   0.3    0.0   99.7  0.01   0.8   0.0  229     0
  0.0   0.2    0.0   99.8  0.01   0.6   0.1  181     0
  0.1   0.2    0.0   99.7  0.01   0.8   0.1  189     0
  0.0   0.3    0.0   99.7  0.01   0.7   0.0  193     0
0.0   0.2    0.0   99.8  0.01   0.7   0.2  204     0
0.1   0.3    0.0   99.7  0.01   0.9   1.0  272     0
0.0   0.3    0.0   99.7  0.01   0.9   0.1  304     0
0.0   0.3    0.0   99.7  0.01   0.9   0.0  212     0

simplempstat.c 코드 예

simplempstat.c 코드를 쓰는 예입니다.

text
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <libperfstat.h>
#include <errno.h>
#include <wpars/wparcfg.h>
static int disp_util_header = 1;
/*simplempstat.c file can be used in two modes:-
1) Auto Mode:It makes use of perfstat_cpu_util API to calculate utilization values,enable ’UTIL_AUTO’ macro for execution in auto mode.
2) Manual Mode: Calculations are done in the current code.
*/
/* #define UTIL_AUTO */
#ifdef  UTIL_AUTO
  #define UTIL_MS 1
  #define UTIL_PCT 0
  #define UTIL_CORE 2
  #define UTIL_PURR 0
  #define UTIL_SPURR 1
  void display_metrics_global_auto(int mode,int cpumode,int count,int interval);
#endif
/* To Check whether malloc is successful or not */
#define CHECK_FOR_MALLOC_NULL(X) {  if ((X) == NULL) {\
                                       perror ("malloc");\
                                       exit(2);\
                                     }\
                                 }
/* Convert 4K pages to MB */
#define AS_MB(X) ((X) * 4096/1024/1024)
/* WPAR ID for global will always be zero */
#define IS_GLOBAL(X) (!(X))
/* Non zero WPAR ID indicates WPAR */
#define IS_WPAR(X) ((X))
/* For WPAR, use NULL else use the actual WPAR ID (for global) */
#define WPAR_ID ((cid)?NULL:&wparid)
/* To store the count of Logical CPUs in the LPAR */
/* Default values for interval and count */
#define INTERVAL_DEFAULT 1
#define COUNT_DEFAULT    1
static int  ncpu, atflag;
static int returncode, count = COUNT_DEFAULT, interval = INTERVAL_DEFAULT;
unsigned long long  last_user, last_sys, last_idle, last_wait, last_timebase;
unsigned long long delta_user, delta_sys, delta_wait, delta_idle, delta_total, delta_timebase;
/* store LPAR level stats */
perfstat_cpu_total_t          *totalcinfo, *totalcinfo_last;
perfstat_memory_total_t       minfo;
perfstat_partition_total_t    pinfo, qinfo;
perfstat_cpu_t        *cinfo, *cinfo_last;
/* stores wpar id for perfstat library */
perfstat_id_wpar_t         wparid;
/* store per WPAR stats */
perfstat_wpar_total_t        winfo;
perfstat_cpu_total_wpar_t    cinfo_wpar;
/* store current WPAR ID */
cid_t cid;
char wpar[MAXCORRALNAMELEN+1];
/* support for remote node statistics collection in a cluster environment */
perfstat_id_node_t nodeid;
char nodename[MAXHOSTNAMELEN];
int nflag = 0;
/* display the usage */
void showusage(char *cmd)
{
   if (!cid)
       fprintf(stderr, "usage: %s [-@ { ALL | WPARNAME } | -n nodename ] [-i <interval in seconds> ] [-c <number of iterations> ]\n", cmd);
   else
       fprintf(stderr, "usage: %s [-i <interval in seconds> ] [-c <number of iterations> ]\n", cmd);
   exit(1);
}
/* Save the current values for the next iteration */
void save_last_values (void)
{
   memcpy( totalcinfo_last, totalcinfo, sizeof(perfstat_cpu_total_t));
   memcpy( cinfo_last, cinfo, sizeof(perfstat_cpu_t));
}
void initialise(void)
{
   totalcinfo = (perfstat_cpu_total_t *)malloc(sizeof(perfstat_cpu_total_t));
   CHECK_FOR_MALLOC_NULL(totalcinfo);
   totalcinfo_last = (perfstat_cpu_total_t *)malloc(sizeof(perfstat_cpu_total_t));
   CHECK_FOR_MALLOC_NULL(totalcinfo_last);
   cinfo = (perfstat_cpu_t *)malloc(sizeof(perfstat_cpu_t) * ncpu);
   CHECK_FOR_MALLOC_NULL(cinfo);
   cinfo_last = (perfstat_cpu_t *)malloc(sizeof(perfstat_cpu_t) * ncpu);
   CHECK_FOR_MALLOC_NULL(cinfo_last);
}
void display_configuration (void)
{
   unsigned long long memlimit;
   double cpulimit;
   int i ,totalcpu;
   /* gather LPAR level data */
   if(nflag) {
      strncpy(nodeid.u.nodename, nodename, MAXHOSTNAMELEN);
      nodeid.spec = NODENAME;
      if (perfstat_partition_total_node(&nodeid, &pinfo, sizeof(perfstat_partition_total_t), 1) <= 0) {
          perror("perfstat_partition_total_node:");
          exit(1);
      }
      if (perfstat_memory_total_node(&nodeid, &minfo, sizeof(perfstat_memory_total_t), 1) <= 0) {
          perror("perfstat_memory_total_node:");
          exit(1);
      }
      totalcpu = perfstat_cpu_node(&nodeid, NULL, sizeof(perfstat_cpu_t), 0);
   }
   else {
      if (perfstat_partition_total(NULL, &pinfo, sizeof(perfstat_partition_total_t), 1) <= 0) {
          perror("perfstat_partition_total:");
          exit(1);
      }
      if (perfstat_memory_total(NULL, &minfo, sizeof(perfstat_memory_total_t), 1) <= 0) {
          perror("perfstat_memory_total:");
          exit(1);
      }
      totalcpu = perfstat_cpu(NULL, NULL, sizeof(perfstat_cpu_t), 0);
   }
   /* print LPAR configuration */
   printf("Purr counter value = %lld \n",pinfo.purr_counter);
   printf("Spurr counter value = %lld \n",pinfo.spurr_counter);
   printf("Free memory = %lld \n",pinfo.real_free);
   printf("Available memory = %lld \n",pinfo.real_avail);
   printf("\nlpar configuration : ");
   printf("lcpus = %d ", totalcpu); /* number of CPUs online */
   printf("mem = %lluMB ", AS_MB(minfo.real_total)); /* real memory */
   printf("ent = %#5.2f\n", (double)pinfo.entitled_proc_capacity/100.0); /* entitled capacity */
}
/*
 * NAME: display_metrics_global
 *       used to display the metrics when called from global
 *
 */
void display_metrics_global(void)
{
   int i;
   perfstat_id_t first;
   strcpy(first.name, FIRST_CPU);
   if(nflag){
       strncpy(nodeid.u.nodename, nodename, MAXHOSTNAMELEN);
       nodeid.spec = NODENAME;
       if (perfstat_cpu_total_node(&nodeid, totalcinfo_last, sizeof(perfstat_cpu_total_t), 1) <= 0){
           perror("perfstat_cpu_total_node:");
           exit(1);
       }
       if (perfstat_cpu_node(&nodeid, cinfo_last, sizeof(perfstat_cpu_t), ncpu) <= 0){
           perror("perfstat_cpu_node:");
           exit(1);
       }
       if (perfstat_partition_total_node(&nodeid, &qinfo, sizeof(perfstat_partition_total_t), 1) <= 0){
           perror("perfstat_partition_total_node:");
           exit(1);
       }
   }
   else{
       if (perfstat_cpu_total(NULL, totalcinfo_last, sizeof(perfstat_cpu_total_t), 1) <= 0){
           perror("perfstat_cpu_total:");
           exit(1);
       }
       if (perfstat_cpu(&first, cinfo_last, sizeof(perfstat_cpu_t), ncpu) <= 0){
           perror("perfstat_cpu:");
           exit(1);
       }
       if (perfstat_partition_total(NULL, &qinfo, sizeof(perfstat_partition_total_t), 1) <= 0){
           perror("perfstat_partition_total:");
           exit(1);
       }
   }
   printf("\n cpu\tuser\tsys\twait\tidle\tstate\n\n");
   while(count)
   {
      sleep(interval);
      if(nflag){
          if (perfstat_cpu_total_node(&nodeid, totalcinfo, sizeof(perfstat_cpu_total_t), 1) <= 0){
              perror("perfstat_cpu_total_node:");
              exit(1);
          }
          if (perfstat_cpu_node(&nodeid, cinfo, sizeof(perfstat_cpu_t), ncpu) <= 0){
              perror("perfstat_cpu_node:");
              exit(1);
          }
          if (perfstat_partition_total_node(&nodeid, &pinfo, sizeof(perfstat_partition_total_t), 1) <= 0){
              perror("perfstat_partition_total_node:");
              exit(1);
          }
      }
      else{
          if (perfstat_cpu_total(NULL, totalcinfo, sizeof(perfstat_cpu_total_t), 1) <= 0){
              perror("perfstat_cpu_total:");
              exit(1);
          }
          if (perfstat_cpu(&first, cinfo, sizeof(perfstat_cpu_t), ncpu) <= 0){
              perror("perfstat_cpu:");
              exit(1);
          }
          if (perfstat_partition_total(NULL, &pinfo, sizeof(perfstat_partition_total_t), 1) <= 0){
              perror("perfstat_partition_total:");
              exit(1);
          }
      }
      for(i = 0; i < ncpu; i++){
          delta_user = cinfo[i].puser - cinfo_last[i].puser;
          delta_sys  = cinfo[i].psys  - cinfo_last[i].psys;
          delta_idle = cinfo[i].pidle - cinfo_last[i].pidle;
          delta_wait = cinfo[i].pwait - cinfo_last[i].pwait;
          delta_total= delta_user + delta_sys + delta_idle + delta_wait;
          delta_timebase = pinfo.timebase_last - qinfo.timebase_last;
     if(!delta_total)
     continue;
          printf("%s\t%#4.1f\t%#4.1f\t%#4.1f\t%#4.1f\t%#4.1d\n",cinfo[i].name,
            ((double)(delta_user)/(double)(delta_total) * 100.0),
            ((double)(delta_sys)/(double)(delta_total) * 100.0),
            ((double)(delta_wait)/(double)(delta_total) * 100.0),
            ((double)(delta_idle)/(double)(delta_total) * 100.0),
            cinfo[i].state);
      }
      delta_user = totalcinfo->puser - totalcinfo_last->puser;
      delta_sys  = totalcinfo->psys  - totalcinfo_last->psys;
      delta_wait = totalcinfo->pwait - totalcinfo_last->pwait;
      delta_idle = totalcinfo->pidle - totalcinfo_last->pidle;
      delta_total= delta_user + delta_sys + delta_idle + delta_wait;
      printf("%s\t%#4.1f\t%#4.1f\t%#4.1f\t%#4.1f\n\n","ALL",((double)(delta_user)/(double)(delta_total) * 100.0),
        ((double)(delta_sys)/(double)(delta_total) * 100.0),
        ((double)(delta_wait)/(double)(delta_total) * 100.0),
        ((double)(delta_idle)/(double)(delta_total) * 100.0));
      count--;
      save_last_values();
   }
}
/*
 *NAME: display_metrics_wpar
 *      used to display the metrics when called from wpar
 *
 */
void display_metrics_wpar(void)
{
   int i;
   char last[5];
   perfstat_id_wpar_t first;
   /*first.spec = WPARNAME;*/
   strcpy(first.name,NULL );
   if (perfstat_wpar_total( NULL, &winfo, sizeof(perfstat_wpar_total_t), 1) <= 0){
       perror("perfstat_wpar_total:");
       exit(1);
   }
   if (perfstat_cpu_total_rset(NULL, totalcinfo_last, sizeof(perfstat_cpu_total_t), 1) <= 0){
       perror("perfstat_cpu_total_rset:");
       exit(1);
   }
   if (perfstat_cpu_rset(NULL, cinfo_last, sizeof(perfstat_cpu_t), ncpu) <= 0){
       perror("perfstat_cpu_rset:");
       exit(1);
   }
   if (perfstat_partition_total(NULL, &qinfo, sizeof(perfstat_partition_total_t), 1) <= 0){
       perror("perfstat_partition_total:");
       exit(1);
   }
   printf("\n cpu\tuser\tsys\twait\tidle\n\n");
   while(count)
   {
      sleep(interval);
      if (perfstat_cpu_total_rset(NULL, totalcinfo, sizeof(perfstat_cpu_total_t), 1) <= 0){
          perror("perfstat_cpu_total_rset:");
          exit(1);
      }
      if (perfstat_cpu_rset(NULL, cinfo, sizeof(perfstat_cpu_t), ncpu) <= 0){
          perror("perfstat_cpu_rset:");
          exit(1);
      }
      if (perfstat_partition_total(NULL, &pinfo, sizeof(perfstat_partition_total_t), 1) <= 0){
          perror("perfstat_partition_total:");
          exit(1);
      }
      for(i=0; i<ncpu; i++){
          delta_user = cinfo[i].puser - cinfo_last[i].puser;
          delta_sys  = cinfo[i].psys  - cinfo_last[i].psys;
          delta_idle = cinfo[i].pidle - cinfo_last[i].pidle;
          delta_wait = cinfo[i].pwait - cinfo_last[i].pwait;
          delta_total= delta_user + delta_sys + delta_idle + delta_wait;
          delta_timebase = pinfo.timebase_last - qinfo.timebase_last;
     if(!delta_total)
     continue;
          printf("%s\t%#4.1f\t%#4.1f\t%#4.1f\t%#4.1f\n",cinfo[i].name,((double)(delta_user)/(double)(delta_total) * 100.0),
                                                             ((double)(delta_sys)/(double)(delta_total) * 100.0),
                                                             ((double)(delta_wait)/(double)(delta_total) * 100.0),
                                                             ((double)(delta_idle)/(double)(delta_total) * 100.0));
      }
      delta_user = totalcinfo->puser - totalcinfo_last->puser;
      delta_sys  = totalcinfo->psys  - totalcinfo_last->psys;
      delta_wait = totalcinfo->pwait - totalcinfo_last->pwait;
      delta_idle = totalcinfo->pidle - totalcinfo_last->pidle;
      delta_total= delta_user + delta_sys + delta_idle + delta_wait;
      if (winfo.type.b.cpu_rset)
          strcpy(last,"RST");
      else
          strcpy(last,"ALL");
      printf("%s\t%#4.1f\t%#4.1f\t%#4.1f\t%#4.1f\n\n",last,((double)(delta_user)/(double)(delta_total) * 100.0),
                                                  ((double)(delta_sys)/(double)(delta_total) * 100.0),
                                                  ((double)(delta_wait)/(double)(delta_total) * 100.0),
                                                  ((double)(delta_idle)/(double)(delta_total) * 100.0));
      count--;
      save_last_values();
   }
}
/*
 * NAME: display_metrics_wpar_from_global
 *       display metrics of wpar when called from global
 *
 */
void display_metrics_wpar_from_global(void)
{
   char last[5];
   int i;
   if (perfstat_wpar_total( &wparid, &winfo, sizeof(perfstat_wpar_total_t), 1) <= 0){
       perror("perfstat_wpar_total:");
       exit(1);
   }
   if (winfo.type.b.cpu_rset)
       strcpy(last,"RST");
   else
       strcpy(last,"ALL");
   strcpy(wparid.u.wparname,wpar);
   if (perfstat_cpu_total_rset(&wparid, totalcinfo_last, sizeof(perfstat_cpu_total_t), 1) <= 0){
       perror("perfstat_cpu_total_rset:");
       exit(1);
   }
   if (perfstat_cpu_rset(&wparid, cinfo_last, sizeof(perfstat_cpu_t), ncpu) <= 0){
       perror("perfstat_cpu_rset:");
       exit(1);
   }
   if (perfstat_partition_total(NULL, &qinfo, sizeof(perfstat_partition_total_t), 1) <= 0){
       perror("perfstat_partition_total:");
       exit(1);
   }
   printf("\n cpu\tuser\tsys\twait\tidle\n\n");
   while(count)
   {
       sleep(interval);
       if (perfstat_cpu_total_rset(&wparid, totalcinfo, sizeof(perfstat_cpu_total_t), 1) <= 0){
           perror("perfstat_cpu_total_rset:");
           exit(1);
       }
       if (perfstat_cpu_rset(&wparid, cinfo, sizeof(perfstat_cpu_t), ncpu) <= 0){
           perror("perfstat_cpu_rset:");
           exit(1);
       }
       if (perfstat_partition_total(NULL, &pinfo, sizeof(perfstat_partition_total_t), 1) <= 0){
           perror("perfstat_partition_total:");
           exit(1);
       }
       for(i = 0; i < ncpu; i++){
           delta_user = cinfo[i].puser - cinfo_last[i].puser;
           delta_sys  = cinfo[i].psys  - cinfo_last[i].psys;
           delta_idle = cinfo[i].pidle - cinfo_last[i].pidle;
           delta_wait = cinfo[i].pwait - cinfo_last[i].pwait;
           delta_total= delta_user + delta_sys + delta_idle + delta_wait;
           delta_timebase = pinfo.timebase_last - qinfo.timebase_last;
      if(!delta_total)
      continue;
       printf("%s\t%#4.1f\t%#4.1f\t%#4.1f\t%#4.1f\n",cinfo[i].name,((double)(delta_user)/(double)(delta_total) * 100.0),
                                                             ((double)(delta_sys)/(double)(delta_total) * 100.0),
                                                             ((double)(delta_wait)/(double)(delta_total) * 100.0),
                                                             ((double)(delta_idle)/(double)(delta_total) * 100.0));
       }
       delta_user = totalcinfo->puser - totalcinfo_last->puser;
       delta_sys  = totalcinfo->psys  - totalcinfo_last->psys;
       delta_wait = totalcinfo->pwait - totalcinfo_last->pwait;
       delta_idle = totalcinfo->pidle - totalcinfo_last->pidle;
       delta_total= delta_user + delta_sys + delta_idle + delta_wait;
       printf("%s\t%#4.1f\t%#4.1f\t%#4.1f\t%#4.1f\n\n",last, ((double)(delta_user)/(double)(delta_total) * 100.0),
                                                  ((double)(delta_sys)/(double)(delta_total) * 100.0),
                                                  ((double)(delta_wait)/(double)(delta_total) * 100.0),
                                                  ((double)(delta_idle)/(double)(delta_total) * 100.0));
       count--;
       save_last_values();
   }
}
#ifdef UTIL_AUTO
void display_metrics_global_auto(int mode,int cpumode,int count,int interval)
{
    float user_core_purr,kern_core_purr,wait_core_purr,idle_core_purr;
    float user_core_spurr,kern_core_spurr,wait_core_spurr,idle_core_spurr,sum_core_spurr;
    u_longlong_t user_ms_purr,kern_ms_purr,wait_ms_purr,idle_ms_purr,sum_ms;
    u_longlong_t user_ms_spurr,kern_ms_spurr,wait_ms_spurr,idle_ms_spurr;
    perfstat_rawdata_t data;
    u_longlong_t delta_purr;
    double phys_proc_consumed, entitlement, percent_ent, delta_sec;
    perfstat_partition_total_t lparstats;
    static perfstat_cpu_t  *oldt,*newt;
    perfstat_cpu_util_t *util;
    int rc,cpu_count,i;
    perfstat_id_t id;
    /* retrieve the metrics */
while(count) {
    /* Print the header for utilization metrics (only once) */
    if (disp_util_header) {
    if(mode==UTIL_PCT)
          printf("\nCPU  %5s %5s %6s %6s %5s  \n",
          "%user", "%sys", "%wait", "%idle", "physc");
    else if(mode==UTIL_MS)
          printf("\nCPU  %5s   %5s   %6s   %6s   %5s \n",
          "user(ms)", "sys(ms)", "wait(ms)", "idle(ms)", "physc");
    else if(mode==UTIL_CORE)
          printf("\nCPU %5s  %5s  %6s  %6s  %5s %5s \n",
          "user", "sys", "wait", "idle", "physc", "state");
       /* first iteration, we only read the data, print the header and save the data */
    }
  cpu_count = perfstat_cpu(NULL, NULL,sizeof(perfstat_cpu_t),0);
  /* check for error */
  if(cpu_count <= 0)
  {
    perror("Error in perfstat_cpu");
    exit(-1);
  }
  /* allocate enough memory */
  oldt = (perfstat_cpu_t *)calloc(cpu_count,sizeof(perfstat_cpu_t));
  if(oldt == NULL)
  {
    perror("Memory Allocation Error");
    exit(-1);
  }
  /* set name to first cpu */
  strcpy(id.name,FIRST_CPU);
  /* ask to get all the structures available in one call */
  rc = perfstat_cpu(&id, oldt, sizeof(perfstat_cpu_t), cpu_count);
  /* check for error */
  if(rc <=0)
  {
    perror("Error in perfstat_cpu");
    exit(-1);
  }
  data.type = UTIL_CPU;
  data.prevstat= oldt;
  data.sizeof_data = sizeof(perfstat_cpu_t);
  data.prev_elems = cpu_count;
  sleep(interval);
  /* Check how many perfstat_cpu_t structures are available after a defined period */
  cpu_count = perfstat_cpu(NULL, NULL,sizeof(perfstat_cpu_t),0);
  /* Check for error */
  if(cpu_count <= 0)
  {
    perror("Error in perfstat_cpu");
    exit(-1);
  }
  data.cur_elems = cpu_count;
  if(data.prev_elems != data.cur_elems)
  {
    perror("The number of CPUs has become different for defined period");
    exit(-1);
  }
  /* allocate enough memory */
  newt = (perfstat_cpu_t *)calloc(cpu_count,sizeof(perfstat_cpu_t));
  util = (perfstat_cpu_util_t *)calloc(cpu_count,sizeof(perfstat_cpu_util_t));
  if(newt == NULL || util == NULL)
  {
   perror("Memory Allocation Error");
   exit(-1);
  }
  data.curstat = newt;
  rc = perfstat_cpu(&id, newt, sizeof(perfstat_cpu_t), cpu_count);
  if(rc <= 0)
  {
    perror("Error in perfstat_cpu");
    exit(-1);
  }
  /* Calculate CPU Utilization Metrics*/
  rc = perfstat_cpu_util(&data, util, sizeof(perfstat_cpu_util_t), cpu_count);
  if(rc <= 0)
  {
    perror("Error in perfstat_cpu_util");
    exit(-1);
  }
switch(mode)
   {
   case  UTIL_PCT:
         for(i=0;i<cpu_count;i++)
         printf("%d %5.1f  %5.1f  %5.1f  %5.1f  %5.7f \n",i,util[i].user_pct,util[i].kern_pct,util[i].wait_pct,util[i].idle_pct,util[i].physical_consumed);
         break;
  case  UTIL_MS:
         for(i=0;i<cpu_count;i++)
         {
         user_ms_purr=((util[i].user_pct*util[i].delta_time)/100.0);
         kern_ms_purr=((util[i].kern_pct*util[i].delta_time)/100.0);
         wait_ms_purr=((util[i].wait_pct*util[i].delta_time)/100.0);
         idle_ms_purr=((util[i].idle_pct*util[i].delta_time)/100.0);
        if(cpumode==UTIL_PURR)
        {
            printf("%d\t %llu\t %llu\t %llu\t %llu\t %5.4f\n",i,user_ms_purr,kern_ms_purr,wait_ms_purr,idle_ms_purr,util[i].physical_consumed);
        }
       else if(cpumode=UTIL_SPURR)
       {
            user_ms_spurr=(user_ms_purr*util[i].freq_pct)/100.0;
            kern_ms_spurr=(kern_ms_purr*util[i].freq_pct)/100.0;
            wait_ms_spurr=(wait_ms_purr*util[i].freq_pct)/100.0;
            sum_ms=user_ms_spurr+kern_ms_spurr+wait_ms_spurr;
            idle_ms_spurr=util[i].delta_time-sum_ms;
            printf("%d\t %llu\t %llu\t %llu\t %llu\t %5.4f \n",i,user_ms_spurr,kern_ms_spurr,wait_ms_spurr,idle_ms_spurr,util[i].physical_consumed);
       }
       }
            break;
  case  UTIL_CORE:
         for(i=0;i<cpu_count;i++)
         {
           user_core_purr=((util[i].user_pct*util[i].physical_consumed)/100.0);
           kern_core_purr=((util[i].kern_pct*util[i].physical_consumed)/100.0);
           wait_core_purr=((util[i].wait_pct*util[i].physical_consumed)/100.0);
           idle_core_purr=((util[i].idle_pct*util[i].physical_consumed)/100.0);
           user_core_spurr=((user_core_purr*util[i].freq_pct)/100.0);
           kern_core_spurr=((kern_core_purr*util[i].freq_pct)/100.0);
           wait_core_spurr=((wait_core_purr*util[i].freq_pct)/100.0);
           if(cpumode==UTIL_PURR)
           {
            printf("%d   %5.4f   %5.4f   %5.4f   %5.4f   %5.4f\n",i,user_core_purr,kern_core_purr,wait_core_purr,idle_core_purr,util[i].physical_consumed);
           }
  else if(cpumode==UTIL_SPURR)
           {
           sum_core_spurr=user_core_spurr+kern_core_spurr+wait_core_spurr;
           idle_core_spurr=util[i].physical_consumed-sum_core_spurr;
            printf("%d    %5.4f   %5.4f   %5.4f   %5.4f   %5.4f \n",i,user_core_spurr,kern_core_spurr,wait_core_spurr,idle_core_spurr,util[i].physical_consumed);
           }
           }
           break;
           default:
           printf("In correct usage\n");
           return;
}
count--;
}
}
#endif
/*
 *NAME: main
 *
 */
int main(int argc,char* argv[])
{
   int c, rc;
   int mode,cpumode;
   cid = corral_getcid();
   while((c = getopt(argc, argv, "@:n:i:c:"))!= EOF){
       switch(c)
       {
           case ’i’:               /* Interval */
                    interval = atoi(optarg);
                    if( interval <= 0 )
                        interval = INTERVAL_DEFAULT;
                    break;
           case ’c’:               /* Number of interations */
                    count = atoi(optarg);
                    if( count <= 0 )
                        count = COUNT_DEFAULT;
                    break;
           case ’n’:               /* Node name in a cluster environment */
                    strncpy(nodename, optarg, MAXHOSTNAMELEN);
                    nodename[MAXHOSTNAMELEN-1] = ’\0’;
                    nflag = 1;
                    break;
           case ’@’:               /* Per-WPAR stats */
                    if (IS_WPAR(cid))
                        showusage(argv[0]);
                    atflag = 1;
                    strcpy(wpar, optarg);
                    break;
           default:
                    /* Invalid arguments. Print the usage and terminate */
                    showusage(argv[0]);
       }
   }
   if (nflag && atflag){
       showusage(argv[0]);
   }
   if(nflag)
   {   /* perfstat_config needs to be called to enable cluster statistics collection */
       rc = perfstat_config(PERFSTAT_ENABLE|PERFSTAT_CLUSTER_STATS, NULL);
       if (rc == -1)
       {
           perror("cluster statistics collection is not available");
           exit(-1);
       }
   }
   if (atflag){
       wparid.spec = WPARNAME;
       strcpy(wparid.u.wparname,wpar);
       ncpu = perfstat_cpu_rset ( &wparid, NULL, sizeof(perfstat_cpu_t), 0);
   }
   else if (nflag){
       nodeid.spec = NODENAME;
       strncpy(nodeid.u.nodename, nodename, MAXHOSTNAMELEN);
       ncpu = perfstat_cpu_node(&nodeid, NULL, sizeof(perfstat_cpu_t), 0);
   }
   else if (IS_GLOBAL(cid)){
       ncpu = perfstat_cpu(NULL, NULL, sizeof(perfstat_cpu_t), 0);
   }
   else{
       ncpu = perfstat_cpu_rset(NULL, NULL, sizeof(perfstat_cpu_t), 0);
   }
   initialise();
   display_configuration();
   if(atflag)
       display_metrics_wpar_from_global();
   else if (cid)
       display_metrics_wpar();
   else
        #ifdef UTIL_AUTO
           printf("Enter CPU mode.\n");
           printf(" 0 PURR \n 1 SPURR \n");
           scanf("%d",&cpumode);
           printf("Enter print mode.\n");
           printf(" 0 PERCENTAGE\n 1 MILLISECONDS\n 2 CORES \n");
           scanf("%d",&mode);
           if((mode>2)&& (cpumode>1))
           {
              printf("Error: Invalid Input\n");
              exit(0);
           }
          display_metrics_global_auto(mode,cpumode,count,interval);
          #else
          display_metrics_global();
          #endif
    if(nflag)
    {   /* Now disable cluster statistics by calling perfstat_config */
       perfstat_config(PERFSTAT_DISABLE|PERFSTAT_CLUSTER_STATS, NULL);
    }
   return(0);
}

이 프로그램은 다음과 비슷한 출력을 냅니다.

text
Purr counter value = 54500189780
Spurr counter value = 54501115744
Free memory = 760099
Available memory = 758179
lpar configuration : lcpus = 8 mem = 4096MB ent =  1.00
 cpu    user    sys     wait    idle    state
cpu0    26.8    54.9     0.0    18.3       1
cpu1     0.0     2.3     0.0    97.7       1
cpu2     0.0     4.7     0.0    95.3       1
cpu3     0.0     2.5     0.0    97.5       1
cpu4     0.0    49.6     0.0    50.4       1
cpu5     0.0    12.7     0.0    87.3       1
cpu6     0.0    10.5     0.0    89.5       1
cpu7     0.0    10.7     0.0    89.3       1
ALL     10.7    24.9     0.0    64.4
영어 원문

perfstat_cpu_util interface

The perfstat_cpu_util interface returns a set of structures of type perfstat_cpu_util_t, which is defined in the libperfstat.h file

The perfstat_cpu_util interface includes the following fields:

  • cpu_id — Holds CPU ID
  • entitlement — Partition's entitlement
  • user_pct — Percentage of utilization in user mode
  • kern_pct — Percentage of utilization in kernel mode
  • idle_pct — Percentage of utilization in idle mode
  • wait_pct — Percentage of utilization in wait mode
  • physical_busy — Physical CPU is busy
  • physical_consumed — Total CPUs consumed by the partition
  • freq_pct — Average frequency over the last interval in percentage
  • entitlement_pct — Percentage of entitlement used
  • busy_pct — Percentage of entitlement busy
  • idle_donated_pct — Percentage of idle cycles donated
  • busy_donated_pct — Percentage of busy cycles donated
  • idle_stolen_pct — Percentage of idle cycles stolen
  • busy_stolen_pct — Percentage of busy cycles stolen
  • float l_user_pct — Percentage of utilization in user mode in terms of the logical processor ticks
  • float l_kern_pct — Percentage of utilization in kernel mode in terms of the logical processor ticks
  • float l_idle_pct — Percentage of utilization in idle mode in terms of the logical processor ticks
  • float l_wait_pct — Percentage of utilization in wait mode in terms of the logical processor ticks
  • u_longlong_t delta_time — Percentage of the delta time in milliseconds for which the utilization is evaluated

Both system utilization and per CPU utilization can be obtained by using theperfstat_cpu_util by mentioning the type field of the perfstat_rawdata_t data structure as UTIL_CPU_TOTAL or UTIL_CPU respectively. UTIL_CPU_TOTAL and UTIL_CPU are the macros, which can be referred in the definition of the perfstat_rawdata_t data structure.

The use of the perrfstat_cpu_util API for system-level utilization follows:

(69줄짜리 예는 위 한글 본문에 그대로 실었습니다.)

The program produces the output similar to the following:

(20줄짜리 예는 위 한글 본문에 그대로 실었습니다.)

The example code to calculate system utilization per CPU, and CPU utilization, by using the perfstat_cpu_util interface follows:

(102줄짜리 예는 위 한글 본문에 그대로 실었습니다.)

The program produces the output similar to the following:

(147줄짜리 예는 위 한글 본문에 그대로 실었습니다.)

Example for simplelparstat.c code

This topic provides an example for using the simplelparstat.c code.

(404줄짜리 예는 위 한글 본문에 그대로 실었습니다.)

The program displays an output that is similar to the following example output:

text
%user  %sys  %wait  %idle physc %entc lbusy vcsw phint
-----  ----  -----  ----- ----- ----- ----- ---- -----
  0.1   0.3    0.0   99.6  0.01   1.1   0.2  285     0
  0.0   0.3    0.0   99.7  0.01   0.8   0.0  229     0
  0.0   0.2    0.0   99.8  0.01   0.6   0.1  181     0
  0.1   0.2    0.0   99.7  0.01   0.8   0.1  189     0
  0.0   0.3    0.0   99.7  0.01   0.7   0.0  193     0
0.0   0.2    0.0   99.8  0.01   0.7   0.2  204     0
0.1   0.3    0.0   99.7  0.01   0.9   1.0  272     0
0.0   0.3    0.0   99.7  0.01   0.9   0.1  304     0
0.0   0.3    0.0   99.7  0.01   0.9   0.0  212     0

Example for simplempstat.c code

This topic provides an example for using the simplempstat.c code.

(622줄짜리 예는 위 한글 본문에 그대로 실었습니다.)

The program displays an output that is similar to the following example output:

(15줄짜리 예는 위 한글 본문에 그대로 실었습니다.)