[AIX 성능 도구 14] 프로파일링 도구 — time·timex·prof·gprof·tprof

핵심 정리

  • 프로파일링은 vmstat·iostat로 CPU 병목을 확인한 뒤, 프로그램의 어느 부분이 CPU를 쓰는지(hot spot) 찾을 때 씁니다. 제대로 동작하는 프로그램과 실제와 비슷한 데이터가 있어야 합니다.
  • time·timex: user+sys와 real을 비교해 CPU 위주인지 I/O 위주인지 가늠합니다(SMP에서는 조심).
  • prof: cc -p로 컴파일 → 실행하면 mon.out → prof. gprof: cc -pg로 컴파일 → gmon.out → gprof(호출 그래프 + 평면 프로파일). 최적화한 코드에는 prof를 쓸 수 없습니다.
  • tprof: 다시 컴파일하지 않고 trace로 프로세스·스레드·함수·소스 줄 단위 CPU 틱을 봅니다. 예: tprof -skex sleep 30, tprof -z -u -p 프로그램 -x 프로그램. 기본은 10ms 시간 기반, -E로 이벤트 기반.
  • (6.1) tprof -a는 대형 페이지(64KB, 16MB)로 바꿨을 때의 변환 미스 예측, tprof -b는 데이터 접근 프로파일링입니다.
항목 내용
버전 AIX 5.3, AIX 6.1 (6.1에서 tprof의 대형 페이지 분석·데이터 프로파일링과 예제가 더해짐)
원문 Performance Tools Guide and Reference — 5.3판 9장(213222쪽), 6.1판 245255쪽
관련 명령어 time, timex, prof, gprof, tprof, trace, gensyms, raso, pmlist

프로파일링 도구로 프로그램의 어느 부분이 가장 자주 실행되는지, 어디서 시간을 가장 많이 쓰는지 알아낼 수 있습니다.

프로파일링 도구는 보통 vmstat나 iostat 같은 기본 도구로 CPU 병목이 성능 문제를 일으킨다는 것을 확인한 뒤에 씁니다.

프로그램의 hot spot을 찾기 전에 완전히 동작하는 프로그램과 실제와 비슷한 데이터 값이 있어야 합니다.

영어 원문

Profiling tools

You can use profiling tools to identify which portions of the program are executed most frequently or where most of the time is spent.

Profiling tools are typically used after a basic tool, such as the vmstat or iostat commands, shows that a CPU bottleneck is causing a performance problem.

Before you begin locating hot spots in your program, you need a fully functional program and realistic data values.

시간 측정 명령

시간 측정 명령은 성능을 기록하며 개선하려는 프로그램을 시험하고 디버그할 때 씁니다.

time 명령의 출력은 분과 초 단위입니다.

text
real    0m26.72s
user    0m26.53s
sys     0m0.03s

timex 명령의 출력은 초 단위입니다.

text
real 26.70
user 26.55
sys  0.02

user+sys CPU 시간을 real 시간과 비교하면 응용 프로그램이 CPU 위주(CPU-bound)인지 I/O 위주(I/O-bound)인지 가늠할 수 있습니다.

참고: SMP 시스템에서 이렇게 할 때는 조심합니다. 자세한 것은 time과 timex의 주의 사항을 봅니다.

timex 명령은 SMIT의 Analysis Tools 메뉴(Performance and Resource Scheduling 아래)에서도 쓸 수 있습니다. timex 명령의 -p와 -s 옵션은 각각 회계(accounting) 데이터와 sar 명령의 데이터를 가져와 보고합니다. -o 옵션은 읽거나 쓴 블록을 보고합니다.

영어 원문

The timing commands

Use the timing commands for testing and debugging programs whose performance you are recording and trying to improve.

The output from the time command is in minutes and seconds, as follows:

text
real    0m26.72s
user    0m26.53s
sys     0m0.03s

The output from the timex command is in seconds, as follows:

text
real 26.70
user 26.55
sys  0.02

Comparing the user+sys CPU time to the real time will give you an idea if your application is CPU-bound or I/O-bound.

Note: Be careful when you do this on an SMP system. For more information, see time and timex Cautions).

The timex command is also available through the SMIT command on the Analysis Tools menu, found under Performance and Resource Scheduling. The -p and -s options of the timex command enable data from accounting (-p) and the sar command (-s) to be accessed and reported. The -o option reports on blocks read or written.

prof 명령

prof 명령은 지정한 프로그램의 외부 기호(external symbol), 곧 루틴마다 CPU 사용 프로파일을 보여 줍니다.

자세히는 다음을 보여 줍니다.

  • 그 기호의 주소와 다음 기호의 주소 사이에서 쓴 실행 시간의 백분율
  • 그 함수가 불린 횟수
  • 호출당 평균 밀리초

prof 명령은 목적 파일(기본 a.out)에 대해 monitor() 서브루틴이 모은 프로파일 데이터를 해석합니다. 목적 파일의 기호 표를 읽어 monitor() 서브루틴이 만든 프로파일 파일(기본 mon.out)과 대응시킵니다. 사용 보고서는 터미널로 보내며 파일로 돌릴 수 있습니다.

prof 명령을 쓰려면 C, FORTRAN, COBOL 소스 프로그램을 -p 옵션으로 컴파일합니다. 그러면 함수 호출을 추적하려고 monitor() 서브루틴을 부르는 특별한 프로파일링 시작 함수가 목적 파일에 들어갑니다. 프로그램을 실행하면 monitor() 서브루틴이 실행 시간을 추적하는 mon.out 파일을 만듭니다. 그러므로 명시적으로 exit하거나 main에서 return하는 프로그램만 mon.out 파일을 만듭니다. 또 -p 플래그를 주면 컴파일러가 다시 컴파일한 함수마다 목적 코드에 mcount() 서브루틴 호출을 넣습니다. 프로그램이 실행되는 동안 부모가 자식 함수를 부를 때마다 자식이 mcount()를 불러 그 부모-자식 쌍의 카운터를 하나 올립니다. 이렇게 함수 호출 횟수를 셉니다.

참고: 최적화한 코드는 prof 명령으로 프로파일링할 수 없습니다.

기본으로 보고서는 CPU 시간 백분율이 큰 순서로 정렬됩니다. -t 옵션을 준 것과 같습니다.

-c 옵션은 호출 횟수가 큰 순서로, -n 옵션은 기호 이름의 알파벳 순서로 정렬합니다.

-s 옵션을 쓰면 요약 파일 mon.sum을 만듭니다. -m 옵션(monitor 데이터가 든 파일 지정)으로 프로파일 파일을 둘 이상 줄 때 유용합니다.

-z 옵션은 호출과 시간이 0인 기호까지 모두 넣습니다.

다른 옵션은 Files Reference의 prof 명령 설명을 봅니다.

다음은 Whetstone 벤치마크(배정밀도) 프로그램을 고친 버전에 대한 prof 출력의 앞부분입니다.

text
# cc -o cwhet -p -lm cwhet.c
# cwhet > cwhet.out
# prof
Name                 %Time     Seconds     Cumsecs  #Calls   msec/call
.main                 32.6       17.63       17.63       1  17630.
.__mcount             28.2       15.25       32.88
.mod8                 16.3        8.82       41.70 8990000      0.0010
.mod9                  9.9        5.38       47.08 6160000      0.0009
.cos                   2.9        1.57       48.65 1920000      0.0008
.exp                   2.4        1.32       49.97  930000      0.0014
.log                   2.4        1.31       51.28  930000      0.0014
.mod3                  1.9        1.01       52.29  140000      0.0072
.sin                   1.2        0.63       52.92  640000      0.0010
.sqrt                  1.1        0.59       53.51
.atan                  1.1        0.57       54.08  640000      0.0009
.pout                  0.0        0.00       54.08      10      0.0
.exit                  0.0        0.00       54.08       1      0.
.free                  0.0        0.00       54.08       2      0.
.free_y                0.0        0.00       54.08       2      0.

이 예에서 mod8()와 mod9() 루틴이 아주 많이 불립니다. 출발점으로 소스 코드를 보고 왜 그렇게 많이 쓰이는지 살펴봅니다. 어떤 루틴이 왜 그렇게 많은 시간을 쓰는지 조사하는 것도 출발점이 될 수 있습니다.

참고: 감시할 프로그램이 fork() 시스템 호출을 쓰면 부모와 자식이 같은 파일(mon.out)을 만든다는 것을 알아 둡니다. 이 문제를 피하려면 자식 프로세스의 현재 디렉터리를 바꿉니다.

영어 원문

The prof command

The prof command displays a profile of CPU usage for each external symbol, or routine, of a specified program.

In detail, it displays the following:

  • The percentage of execution time spent between the address of that symbol and the address of the next

  • The number of times that function was called

  • The average number of milliseconds per call

The prof command interprets the profile data collected by the monitor() subroutine for the object file (a.out by default), reads the symbol table in the object file, and correlates it with the profile file (mon.out by default) generated by the monitor() subroutine. A usage report is sent to the terminal, or can be redirected to a file.

To use the prof command, use the -p option to compile a source program in C, FORTRAN, or COBOL. This inserts a special profiling startup function into the object file that calls the monitor() subroutine to track function calls. When the program is executed, the monitor() subroutine creates a mon.out file to track execution time. Therefore, only programs that explicitly exit or return from the main program cause the mon.out file to be produced. Also, the -p flag causes the compiler to insert a call to the mcount() subroutine into the object code generated for each recompiled function of your program. While the program runs, each time a parent calls a child function, the child calls the mcount() subroutine to increment a distinct counter for that parent-child pair. This counts the number of calls to a function.

Note: You cannot use the prof command for profiling optimized code.

By default, the displayed report is sorted by decreasing percentage of CPU time. This is the same as when specifying the -t option.

The -c option sorts by decreasing number of calls and the -n option sorts alphabetically by symbol name.

If the -s option is used, a summary file mon.sum is produced. This is useful when more than one profile file is specified with the -m option (the -m option specifies files containing monitor data).

The -z option includes all symbols, even if there are zero calls and time associated.

Other options are available and explained in the prof command in the Files Reference.

The following example shows the first part of the prof command output for a modified version of the Whetstone benchmark (Double Precision) program.

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

In this example, we see many calls to the mod8() and mod9() routines. As a starting point, examine the source code to see why they are used so much. Another starting point could be to investigate why a routine requires so much time.

Note: If the program you want to monitor uses a fork() system call, be aware that the parent and the child create the same file (mon.out). To avoid this problem, change the current directory of the child process.

gprof 명령

gprof 명령은 C, FORTRAN, COBOL 프로그램의 실행 프로파일을 만듭니다.

호출된 서브루틴의 통계가 호출한 프로그램의 프로파일에 들어갑니다. gprof 명령은 프로그램이 CPU 자원을 어떻게 쓰는지 알아내는 데 유용합니다. 대략 prof 명령의 상위 집합으로, 정보를 더 주고 코드의 활발한 부분을 더 잘 보여 줍니다.

영어 원문

The gprof command

The gprof command produces an execution profile of C, FORTRAN, or COBOL programs.

The statistics of called subroutines are included in the profile of the calling program. The gprof command is useful in identifying how a program consumes CPU resources. It is roughly a superset of the prof command, giving additional information and providing more visibility to active sections of code.

gprof 명령의 구현

소스 코드는 -pg 옵션으로 컴파일해야 합니다.

그러면 프로파일링용으로 컴파일한 라이브러리 루틴 버전이 링크되고, 이름을 지정한 목적 파일(기본 a.out)의 기호 표를 읽어 호출 그래프 프로파일 파일(기본 gmon.out)과 대응시킵니다. 곧 컴파일러가 다시 컴파일한 함수마다 목적 코드에 mcount() 함수 호출을 넣습니다. mcount() 함수는 부모가 자식 함수를 부를 때마다 셉니다. 또 각 루틴에서 쓴 시간을 추정하도록 monitor() 함수가 켜집니다.

gprof 명령은 쓸모 있는 보고서 두 가지를 만듭니다.

  • 호출 그래프 프로파일(call-graph profile): 루틴과 그 자손을 CPU 시간이 큰 순서로 보여 줍니다. 어떤 루틴을 가장 자주 부른 부모 루틴과, 어떤 루틴이 가장 자주 부른 자식 루틴을 알 수 있습니다.
  • 평면 프로파일(flat profile): prof 출력과 비슷하게 루틴별 사용량과 호출 횟수를 보여 줍니다.

각 보고서는 출력 열을 설명하는 부분으로 시작합니다. -b 옵션으로 이 설명을 뺄 수 있습니다.

요약은 -s, 사용량이 0인 루틴도 보려면 -z를 씁니다.

프로그램을 실행하면 통계가 gmon.out 파일에 모입니다. 통계에는 다음이 들어갑니다.

  • 적재된 실행 프로그램과 공유 라이브러리 객체의 이름
  • 각 프로그램 세그먼트에 할당된 가상 메모리 주소
  • 부모-자식마다의 mcount() 데이터
  • 각 프로그램 세그먼트에 쌓인 밀리초

나중에 gprof 명령을 실행하면 a.out과 gmon.out 파일을 읽어 두 보고서를 만듭니다. 호출 그래프 프로파일이 먼저, 평면 프로파일이 뒤에 나옵니다. 평면 프로파일을 먼저 보면 대부분의 궁금증이 풀릴 수 있으므로 gprof 출력은 파일로 돌리는 것이 좋습니다.

다음은 cwhet 벤치마크 프로그램의 프로파일링 예입니다. prof 명령에서도 쓴 예입니다.

text
# cc -o cwhet -pg -lm cwhet.c
# cwhet > cwhet.out
# gprof cwhet > cwhet.gprof

호출 그래프 프로파일

호출 그래프 프로파일은 cwhet.gprof 파일의 첫 부분입니다.

다음은 cwhet.gprof 파일의 예입니다.

text
granularity: each sample hit covers 4 byte(s) Time: 62.85 seconds
                                  called/total       parents
index  %time    self descendents  called+self    name           index
                                  called/total       children
               19.44       21.18       1/1           .__start [2]
[1]     64.6   19.44       21.18       1         .main [1]
                8.89        0.00 8990000/8990000     .mod8 [4]
                5.64        0.00 6160000/6160000     .mod9 [5]
                1.58        0.00  930000/930000      .exp [6]
                1.53        0.00 1920000/1920000     .cos [7]
                1.37        0.00  930000/930000      .log [8]
                1.02        0.00  140000/140000      .mod3 [10]
                0.63        0.00  640000/640000      .atan [12]
                0.52        0.00  640000/640000      .sin [14]
                0.00        0.00      10/10          .pout [27]
-----------------------------------------------
                                                     <spontaneous>
[2]     64.6    0.00       40.62                 .__start [2]
               19.44       21.18       1/1           .main [1]
                0.00        0.00       1/1           .exit [37]
-----------------------------------------------

보통 호출 그래프 보고서는 각 열의 설명으로 시작하지만 이 예에서는 뺐습니다. 열 머리는 함수 종류(현재 함수, 현재 함수의 부모, 현재 함수의 자식)에 따라 다릅니다. 현재 함수는 줄 앞의 대괄호 색인으로 표시합니다. 함수는 쓴 CPU 시간이 큰 순서로 나열됩니다.

이 보고서를 읽으려면 왼쪽 열의 첫 색인 [1]을 봅니다. .main 함수가 현재 함수입니다. .__start가 시작했고(부모 함수는 현재 함수 위에 있음), .main은 다시 .mod8과 .mod9을 부릅니다(자식 함수는 현재 함수 아래에 있음). .main의 누적 시간은 모두 .__start로 전달됩니다. 현재 함수의 자식들의 self와 descendents 열을 더하면 현재 함수의 descendents 값이 됩니다. 현재 함수는 부모가 여럿일 수 있으며, 실행 시간은 불린 횟수에 따라 부모 함수들에 나뉩니다.

평면 프로파일

평면 프로파일 예는 cwhet.gprof 파일의 둘째 부분입니다.

다음은 cwhet.gprof 파일의 예입니다.

text
granularity: each sample hit covers 4 byte(s) Total time: 62.85 seconds
  %   cumulative   self              self     total
 time   seconds  seconds     calls  ms/call  ms/call  name
 30.9      19.44    19.44        1 19440.00 40620.00  .main [1]
 30.5      38.61    19.17                             .__mcount [3]
 14.1      47.50     8.89  8990000     0.00     0.00  .mod8 [4]
  9.0      53.14     5.64  6160000     0.00     0.00  .mod9 [5]
  2.5      54.72     1.58   930000     0.00     0.00  .exp [6]
  2.4      56.25     1.53  1920000     0.00     0.00  .cos [7]
  2.2      57.62     1.37   930000     0.00     0.00  .log [8]
  2.0      58.88     1.26                             .qincrement [9]
  1.6      59.90     1.02   140000     0.01     0.01  .mod3 [10]
  1.2      60.68     0.78                             .__stack_pointer [11]
  1.0      61.31     0.63   640000     0.00     0.00  .atan [12]
  0.9      61.89     0.58                             .qincrement1 [13]
  0.8      62.41     0.52   640000     0.00     0.00  .sin [14]
  0.7      62.85     0.44                             .sqrt [15]
  0.0      62.85     0.00      180     0.00     0.00  .fwrite [16]
  0.0      62.85     0.00      180     0.00     0.00  .memchr [17]
  0.0      62.85     0.00       90     0.00     0.00  .__flsbuf [18]
  0.0      62.85     0.00       90     0.00     0.00  ._flsbuf [19]

평면 프로파일은 호출 그래프 프로파일보다 훨씬 간단하며 prof 명령의 출력과 아주 비슷합니다. 주로 볼 열은 self seconds와 calls입니다. 각 함수에서 쓴 CPU 초와 각 함수가 불린 횟수입니다. 그다음 볼 열은 self ms/call(함수 본문 자체가 쓴 CPU 시간)과 total ms/call(함수 본문과 그 함수가 부른 자손 함수에서 쓴 시간)입니다.

보통 목록 맨 위의 함수가 최적화 후보이지만, 함수가 몇 번 불리는지도 생각해야 합니다. 한 번 불리는 코드를 크게 고치는 것보다 자주 불리는 함수를 조금 개선하는 편이 쉬울 때가 있습니다.

마지막에는 다음과 같은 상호 참조 색인이 나옵니다.

text
Index by function name
  [18] .__flsbuf            [37] .exit                 [5] .mod9
  [34] .__ioctl              [6] .exp                 [43] .moncontrol
  [20] .__mcount            [39] .expand_catname      [44] .monitor
   [3] .__mcount            [32] .free                [22] .myecvt
  [23] .__nl_langinfo_std   [33] .free_y              [28] .nl_langinfo
  [11] .__stack_pointer     [16] .fwrite              [27] .pout
  [24] ._doprnt             [40] .getenv              [29] .printf
  [35] ._findbuf            [41] .ioctl                [9] .qincrement
  [19] ._flsbuf             [42] .isatty              [13] .qincrement1
  [36] ._wrtchk              [8] .log                 [45] .saved_category_nam
  [25] ._xflsbuf             [1] .main                [46] .setlocale
  [26] ._xwrite             [17] .memchr              [14] .sin
  [12] .atan                [21] .mf2x2               [31] .splay
  [38] .catopen             [10] .mod3                [15] .sqrt
   [7] .cos                  [4] .mod8                [30] .write

참고: 감시할 프로그램이 fork() 시스템 호출을 쓰면 기본으로 부모와 자식이 같은 파일 gmon.out을 만든다는 것을 알아 둡니다. 이 문제를 피하려면 GPROF 환경 변수를 씁니다. GPROF 환경 변수로 다중 스레드 응용 프로그램도 프로파일링할 수 있습니다.

영어 원문

Implementation of the gprof command

The source code must be compiled with the -pg option.

This action links in versions of library routines compiled for profiling and reads the symbol table in the named object file (a.out by default), correlating it with the call graph profile file (gmon.out by default). This means that the compiler inserts a call to the mcount() function into the object code generated for each recompiled function of your program. The mcount() function counts each time a parent calls a child function. Also, the monitor() function is enabled to estimate the time spent in each routine.

The gprof command generates two useful reports:

  • The call-graph profile, which shows the routines, in descending order by CPU time, plus their descendants. The profile permits you to understand which parent routines called a particular routine most frequently and which child routines were called by a particular routine most frequently.

  • The flat profile of CPU usage, which shows the usage by routine and number of calls, similar to the prof output.

Each report section begins with an explanatory part describing the output columns. You can suppress these pages by using the -b option.

Use -s for summaries and -z to display routines with zero usage.

Where the program is executed, statistics are collected in the gmon.out file. These statistics include the following:

  • The names of the executable program and shared library objects that were loaded

  • The virtual memory addresses assigned to each program segment

  • The mcount() data for each parent-child

  • The number of milliseconds accumulated for each program segment

Later, when the gprof command is issued, it reads the a.out and gmon.out files to generate the two reports. The call-graph profile is generated first, followed by the flat profile. It is best to redirect the gprof output to a file, because browsing the flat profile first might answer most of your usage questions.

The following example shows the profiling for the cwhet benchmark program. This example is also used in The prof command:

text
# cc -o cwhet -pg -lm cwhet.c
# cwhet > cwhet.out
# gprof cwhet > cwhet.gprof

The call-graph profile

The call-graph profile is the first part of the cwhet.gprof file.

The following is an example of the cwhet.gprof file:

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

Usually the call graph report begins with a description of each column of the report, but it has been deleted in this example. The column headings vary according to type of function (current, parent of current, or child of current function). The current function is indicated by an index in brackets at the beginning of the line. Functions are listed in decreasing order of CPU time used.

To read this report, look at the first index [1] in the left-hand column. The .main function is the current function. It was started by .__start (the parent function is on top of the current function), and it, in turn, calls .mod8 and .mod9 (the child functions are beneath the current function). All the accumulated time of .main is propagated to .__start. The self and descendents columns of the children of the current function add up to the descendents entry for the current function. The current function can have more than one parent. Execution time is allocated to the parent functions based on the number of times they are called.

Flat profile

The flat profile sample is the second part of the cwhet.gprof file.

The following is an example of the cwhet.gprof file:

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

The flat profile is much less complex than the call-graph profile and very similar to the output of the prof command. The primary columns of interest are the self seconds and the calls columns. These reflect the CPU seconds spent in each function and the number of times each function was called. The next columns to look at are self ms/call (CPU time used by the body of the function itself) and total ms/call (time in the body of the function plus any descendent functions called).

Normally, the top functions on the list are candidates for optimization, but you should also consider how many calls are made to the function. Sometimes it can be easier to make slight improvements to a frequently called function than to make extensive changes to a piece of code that is called once.

A cross reference index is the last item produced and looks similar to the following:

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

Note: If the program you want to monitor uses a fork() system call, be aware that by default, the parent and the child create the same file, gmon.out. To avoid this problem, use the GPROF environment variable. You can also use the GPROF environment variable to profile multi-threaded applications.

tprof 명령

일반적인 프로그램 실행은 응용 프로그램 코드, 라이브러리 서브루틴, 커널 서비스가 여러 비율로 섞인 것입니다. 튜닝하지 않은 프로그램은 CPU 사이클의 대부분을 특정 문장이나 서브루틴에서 쓰는 일이 많습니다.

tprof 명령으로 어느 문장이나 서브루틴을 살펴봐야 할지 알아낼 수 있습니다.

tprof 명령은 프로세스 ID와 이름마다 CPU 사용을 자세히 보여 주는 다재다능한 프로파일러입니다. 응용 프로그램 수준, 루틴 수준, 소스 문장 수준까지 프로파일링하며, 전체 보기와 상세 보기를 모두 줍니다. 또 커널 확장, strip한 실행 프로그램과 라이브러리도 프로파일링할 수 있습니다. stripnm 명령이 기호 표를 만들 수 있는 대부분의 실행 프로그램은 서브루틴 수준까지 프로파일링합니다. tprof 명령은 다음 컴파일러로 만든 프로그램을 모두 프로파일링할 수 있습니다.

  • C
  • C++
  • FORTRAN
  • Java

tprof 명령은 CPU 활동만 프로파일링합니다. 메모리나 디스크 같은 다른 시스템 자원은 프로파일링하지 않습니다.

tprof 명령은 JPA(-x java -Xrunjpa)로 Java 프로그램을 프로파일링해 Java JIT(Just-in-Time) 소스 줄 번호와 명령어를 모을 수 있습니다. 이때 -Xrunjpa에 다음 매개변수를 더합니다.

  • source=1: IBM JRE(Java Runtime Environment) 1.5.0이 설치되어 있으면 JIT 소스 줄 수집을 켭니다.
  • instructions=1: JIT 명령어 수집을 켭니다.
영어 원문

The tprof command

The typical program execution is a variable combination of application code, library subroutines, and kernel services. Frequently, programs that have not been tuned expend most of their CPU cycles in certain statements or subroutines.

You can determine which particular statements or subroutines to examine with the tprof command.

The tprof command is a versatile profiler that provides a detailed profile of CPU usage by every process ID and name. It further profiles at the application level, routine level, and even to the source statement level and provides both a global view and a detailed view. In addition, the tprof command can profile kernel extensions, stripped executable programs, and stripped libraries. It does subroutine-level profiling for most executable programs on which the stripnm command produces a symbols table. The tprof command can profile any program produced by any of the following compilers:

  • C

  • C++

  • FORTRAN

  • Java™

The tprof command only profiles CPU activity. It does not profile other system resources, such as memory or disks.

The tprof command can profile Java programs using Java Persistence API (JPA) (-x java -Xrunjpa) to collect Java Just-in-Time (JIT) source line numbers and instructions, if the following parameters are added to -Xrunjpa:

  • source=1; if IBM Java Runtime Environment (JRE) 1.5.0 is installed, this parameter enables JIT source line collecting.

  • instructions=1; enables JIT instructions collecting.

시간 기반 프로파일링

시간 기반 프로파일링은 기본 프로파일링 모드이며, 10밀리초마다 일어나는 감소기(decrementer) 인터럽트로 동작합니다.

시간 기반 프로파일링에서 tprof 명령은 인터럽트가 꺼져 있을 때 루틴의 주소를 알 수 없습니다. 인터럽트가 꺼져 있는 동안의 틱은 모두 unlock_enable() 루틴에 매겨집니다.

영어 원문

Time-based profiling

Time-based profiling is the default profiling mode and it is triggered by the decrementer interrupt, which occurs every 10 milliseconds.

With time-based profiling, the tprof command cannot determine the address of a routine when interrupts are disabled. While interrupts are disabled, all ticks are charged to the unlock_enable() routines.

이벤트 기반 프로파일링

이벤트 기반 프로파일링은 소프트웨어 기반 이벤트나 프로세서에서 일어나는 성능 모니터 이벤트 가운데 하나로 동작합니다.

시간 기반 프로파일링보다 이벤트 기반 프로파일링이 나은 점은 다음과 같습니다.

  • 인터럽트가 꺼져 있을 때도 루틴 주소가 보입니다.
  • 프로파일링 이벤트를 바꿀 수 있습니다.
  • 표본 수집 빈도를 바꿀 수 있습니다.

이벤트 기반 프로파일링에서는 인터럽트가 꺼져 있는 동안의 틱이 올바른 루틴에 매겨집니다. 또 프로파일링 이벤트와 표본 수집 빈도를 고를 수 있습니다. 프로파일링 이벤트는 인터럽트를 일으킬 계기를, 표본 수집 빈도는 인터럽트가 얼마나 자주 일어날지를 정합니다. 프로파일링 이벤트가 지정한 횟수만큼 일어나면 인터럽트가 생기고 실행 중인 명령어가 기록됩니다.

기본 프로파일링 이벤트는 프로세서 사이클입니다. 소프트웨어 기반 이벤트에는 다음이 있습니다.

  • 에뮬레이션 인터럽트(EMULATION)
  • 정렬(alignment) 인터럽트(ALIGNMENT)
  • 명령어 SLB(Segment Lookaside Buffer) 미스(ISLBMISS)
  • 데이터 SLB 미스(DSLBMISS)

소프트웨어 기반 이벤트의 표본 수집 빈도는 밀리초 단위로 지정하며 범위는 1~500밀리초, 기본은 10밀리초입니다.

다음 명령은 5밀리초마다 인터럽트를 일으켜 마지막 에뮬레이션 인터럽트의 레코드를 가져옵니다.

text
# tprof -E EMULATION -f 5

다음 명령은 100밀리초마다 인터럽트를 일으켜 SIAR(Sampled Instruction Address Register)의 내용을 기록합니다.

text
# tprof -E -f 100

다른 종류의 성능 모니터 이벤트에는 다음이 있습니다.

  • 완료된 명령어
  • 캐시 미스

시스템의 프로세서가 지원하는 성능 모니터 이벤트 목록은 pmlist 명령으로 봅니다. 고른 성능 모니터 이벤트는 PM_INST_CMPL 이벤트도 들어 있는 그룹에서 골라야 합니다. 이런 이벤트의 표본 수집 빈도는 이벤트가 일어난 횟수로 지정하며 범위는 10,000~MAXINT회, 기본은 10,000회입니다.

다음 명령은 프로세서가 명령어 50,000개를 완료할 때마다 인터럽트를 일으킵니다.

text
# tprof -E PM_INST_CMPL -f 50000

이벤트 기반 프로파일링은 실행 중인 명령어 가까이 있는 명령어의 주소를 담은 SIAR를 씁니다. 예를 들어 프로파일링 이벤트가 PM_FPU0_FIN(부동 소수점 장치 0이 결과를 냄)이면 SIAR에는 그 부동 소수점 명령어가 아니라 그 근처의 다른 명령어가 들어 있을 수 있습니다. 이 점은 성능 모니터 이벤트 기반 프로파일링에서 더 중요합니다. 실제로 이 근접성 때문에 POWER4 이후 시스템에서는 성능 모니터 프로파일링 이벤트로 표시(marked) 이벤트를 쓰는 것을 권합니다. 표시 이벤트에는 PM_MRK 접두사가 붙습니다.

프로파일링 이벤트, 표본 수집 빈도, 작업 부하의 조합에 따라 인터럽트가 너무 자주 일어나 시스템이 대부분의 시간을 인터럽트 처리기에서 쓸 수 있습니다. tprof 명령은 연속된 두 인터럽트 사이에 완료된 명령어 수를 추적해 이 상황을 감지합니다. 그 수가 허용 한계 아래로 다섯 번 떨어지면 trace 수집을 멈춥니다. 보고서는 그래도 만들어지며 오류 메시지가 나옵니다. 기본 임계값은 명령어 1,000개입니다.

영어 원문

Event-based profiling

Event-based profiling is triggered by any one of the software-based events or any Performance Monitor event that occurs on the processor.

The primary advantages of event-based profiling over time-based profiling are the following:

  • The routine addresses are visible when interrupts are disabled.

  • The ability to vary the profiling event

  • The ability to vary the sampling frequency

With event-based profiling, ticks that occur while interrupts are disabled are charged to the proper routines. Also, you can select the profiling event and sampling frequency. The profiling event determines the trigger for the interrupt and the sampling frequency determines how often the interrupt occurs. After the specified number of occurrences of the profiling event, an interrupt is generated and the executing instruction is recorded.

The default type of profiling event is processor cycles. The following are various types of software-based events:

  • Emulation interrupts (EMULATION)

  • Alignment interrupts (ALIGNMENT)

  • Instruction Segment Lookaside Buffer misses (ISLBMISS)

  • Data Segment Lookaside Buffer misses (DSLBMISS)

The sampling frequency for the software-based events is specified in milliseconds and the supported range is 1 to 500 milliseconds. The default sampling frequency is 10 milliseconds.

The following command generates an interrupt every 5 milliseconds and retrieves the record for the last emulation interrupt:

text
# tprof -E EMULATION -f 5

The following command generates an interrupt every 100 milliseconds and records the contents of the Sampled Instruction Address Register, or SIAR:

text
# tprof -E -f 100

The following are other types of Performance Monitor events:

  • Completed instructions

  • Cache misses

For a list of all the Performance Monitor events that are supported on the processors of the system, use the pmlist command. The chosen Performance Monitor event must be taken in a group where we can also find the PM_INST_CMPL Performance Monitor event. The sampling frequency for these events is specified in the number of occurrences of the event. The supported range is 10,000 to MAXINT occurrences. The default sampling frequency is 10,000 occurrences.

The following command generates an interrupt after the processor completes 50,000 instructions:

text
# tprof -E PM_INST_CMPL -f 50000

Event-based profiling uses the SIAR, which contains the address of an instruction close to the executing instruction. For example, if the profiling event is PM_FPU0_FIN, which means the floating point unit 0 produces a result, the SIAR might not contain that floating point instruction but might contain another instruction close to it. This is more relevant for profiling based on Performance Monitor events. In fact for the proximity reason, on systems based on POWER4 and later, it is recommended that the Performance Monitor profiling event be one of the marked events. Marked events have the PM_MRK prefix.

Certain combinations of profiling event, sampling frequency, and workload might cause interrupts to occur at such a rapid rate that the system spends most of its time in the interrupt handler. The tprof command detects this condition by keeping track of the number of completed instructions between two consecutive interrupts. When the tprof command detects five occurrences of the count falling below the acceptable limit, the trace collection stops. Reports are still generated and an error message is displayed. The default threshold is 1,000 instructions.

(6.1) 대형 페이지 분석

tprof -a 명령은 대표적인 응용 프로그램 실행에서 프로파일 trace를 모아, 응용 프로그램 데이터 공간의 부분들을 다른 페이지 크기에 매핑했을 때의 성능 예측을 만듭니다.

대형 페이지 분석은 trace의 정보로, 응용 프로그램의 다음 네 메모리 영역 가운데 하나를 다른 페이지 크기에 매핑했을 때의 변환 버퍼(TLB) 성능을 예측합니다.

  • 정적 응용 프로그램 데이터(초기화된 데이터와 초기화되지 않은 데이터)
  • 응용 프로그램 힙(동적으로 할당한 데이터)
  • 스택
  • 응용 프로그램 텍스트

운영 체제가 지원하는 페이지 크기마다 성능 예측을 줍니다. 첫 예측은 네 메모리 영역을 모두 기본 4KB 페이지에 매핑하는 기준 예측입니다. 그다음 예측은 한 번에 한 영역씩 다른 페이지 크기에 매핑합니다. 예측마다 페이지 크기, 네 영역을 모두 담는 데 필요한 페이지 수, 변환 미스 점수, 콜드(cold) 변환 미스 점수를 보고합니다.

요약 절에는 프로파일링한 프로세스와 통계(메모리 참조 수·비율, 모델링한 메모리 참조, malloc 호출 수, free 호출 수)가 나옵니다.

결과를 해석하는 법

변환 미스 점수는 변환 미스율을 나타내는 지표로, 0(변환 미스 없음)에서 1(모든 참조가 변환 미스)까지입니다.

변환 미스율은 다음과 같이 정의합니다.

text
Translation miss rate = (Number of translation misses)/(Number of translation buffer accesses)

변환 미스 점수는 표본으로 뽑은 참조를 바탕으로 하므로 실제 변환 미스율과 다릅니다. 표본 수집은 위 식의 분모(변환 버퍼 접근 수)를 분자(변환 미스 수)보다 빨리 줄이는 효과가 있습니다. 그래서 표본 수집 비율이 높아질수록 변환 미스 점수는 실제 변환 미스율을 과대평가하는 경향이 있습니다. 따라서 변환 점수는 실제 변환 미스율의 예측값이 아니라, 여러 예측의 효과를 비교하는 상대적인 척도로 해석해야 합니다.

페이지 크기를 키우면 변환 미스 점수가 직접 줄어듭니다. 성능 예측 보고서에는 콜드 변환 미스 점수(강제(compulsory) 미스)와 전체 변환 미스 점수(강제 미스와 용량(capacity) 미스)가 모두 들어갑니다. 콜드 변환 미스 점수는 유용한 하한입니다. 페이지 크기를 키워 변환 미스 점수가 콜드 변환 미스 점수까지 내려갔다면 용량 변환 미스는 모두 없어진 것이므로, 페이지 크기를 더 키워도 이득은 거의 없습니다.

프로세스의 성능 예측은 다음과 비슷합니다.

text
Modeled region for the process ./workload [661980]
Region   Start               End                 Size (KB)   %MemRef
======   =================   =================   =========   =======
heap     0x1100059b0         0x1207b0b60         269996.43     74.45
data     0x110000710         0x11000598c             20.63      1.55
stack    0xffffffffffced10   0xfffffffffffffe0      196.71     20.44
text     0x100000288         0x100053710            333.14      2.56

Performance projection for the process ./workload [661980]
Region   PageSize   # Pages   TMissScore         ColdTMissScore
======   ========   =======   ================   ================
heap     4 KB         67500   0.92343 (100.0%)   0.09234 (100.0%)
heap     64 KB         4219   0.53615 ( 45.0%)   0.02744 ( 30.0%)
heap     16 MB           17   0.00010 ( 00.1%)   0.00002 ( 00.1%)
data     4 KB             6   0.53615 (100.0%)   0.02744 (100.0%)
data     64 KB            1   0.00053 ( 00.1%)   0.00009 ( 00.1%)
data     16 MB            1   0.00053 ( 00.1%)   0.00009 ( 00.1%)
stack    4 KB            50   0.53615 (100.0%)   0.02744 (100.0%)
stack    64 KB            4   0.05361 ( 10.0%)   0.00274 ( 10.0%)
stack    16 MB            1   0.00053 ( 00.1%)   0.00009 ( 00.1%)
text     4 KB            84   0.53615 (100.0%)   0.04744 (100.0%)
text     64 KB            6   0.05361 ( 10.0%)   0.00274 ( 10.0%)
text     16 MB            1   0.00053 ( 00.1%)   0.00009 ( 00.1%)

데이터 프로파일링

tprof -b 명령은 기본 데이터 프로파일링을 켜고 데이터 접근 정보를 모읍니다.

요약 절은 프로세스마다 커널 데이터, 라이브러리 데이터, 사용자 전역 데이터, stackheap 영역의 접근 정보를 보고합니다. 다음 예와 같습니다.

프로세스 Freq Total Kernel User Shared Other
tlbref 1 60.49 0.07 59.71 0.38 0.00
/usr/bin/dd 1 39.30 26.75 11.82 0.73 0.00
tprof 2 0.21 0.21 0.00 0.33 0.00
Total 20 100.00 27.03 71.53 1.44 0.00

다음은 프로세스마다의 데이터 프로파일링 보고서 예입니다.

text
Process        PID       TID      Total   Kernel    User   Shared   Other
tlbref         327688    757943   60.49   0/07     59.71    0.38    0.00
    Kernel: 0.04%  lib: 0.00%  u_global: 0.00%  stackheap: u_global: 0.00%  unresolved: 99.42%
tprof          3278000   792863    0.21    0.21     0.00    0.00    0.00
    kernel: 0.20%  lib: 0.00%  u_global: 0.00%  stackheap 0.00%  unresolved: 0.01%
/usr/bin/dd    323768    974985   39.30   26.75    11.82    0.73    0.00
    kernel: 12.86%  lib: 0.00%  u_global: 7.80%  stackheap: 2.42%  unresolved: 2.18%
Total                            100.00   27.03    99.01    1.44    0.00

-s, -u, -k, -e 플래그와 함께 쓰면 tprof의 데이터 프로파일링은 공유 라이브러리, 바이너리, 커널, 커널 확장에서 가장 많이 쓰인 데이터 구조(내보낸 데이터 기호)를 보고합니다. -B 플래그는 데이터 구조를 쓰는 함수도 보고합니다.

다음은 /usr/bin/dd 프로세스의 데이터 프로파일링 보고서 예입니다. 모은 표본으로 보면 /usr/bin/dd 프로세스에서 가장 많이 쓰인 데이터 구조는 __start입니다. 데이터 구조 아래에는 그것을 쓰는 함수 목록(오른쪽 정렬)이 몫과 출처와 함께 나옵니다.

text
Total % For /usr/bin/dd[323768] (/usr/bin/dd) = 11.69
Subroutine       % Source
.noconv      11.29 /usr/bin/dd
     .main    0.14 /usr/bin/dd
     .read    0.07 glink.s
  .setobuf    0.05 /usr/bin/dd
    .rpipe    0.04 /usr/bin/dd
     .flsh    0.04 /usr/bin/dd
    .write    0.04 glink.s
     .wbuf    0.02 /usr/bin/dd
     .rbuf    0.02 /usr/bin/dd
Data             % Source
__start       7.80 /usr/bin/dd
   .noconv    6.59 /usr/bin/dd
     .main    0.14 /usr/bin/dd
     .read    0.04 glink.s
     .wbuf    0.02 /usr/bin/dd
    .write    0.02 glink.s
     .flsh    0.102 /usr/bin/dd
영어 원문

Large page analysis

The tprof -a command collects profile trace from a representative application run and produces performance projections for mapping different portions of the application's data space to different page sizes.

Large Page Analysis uses the information in the trace to project translation buffer performance when mapping any of the following four application memory regions to a different page size:

  • static application data (initialized and uninitialized data)

  • application heap (dynamically allocated data)

  • stack

  • application text

The performance projections are provided for each of the page sizes supported by the operating system. The first performance projection is a baseline projection for mapping all four memory regions to the default 4 KB pages. Subsequent projections map one region at a time to a different page size. The statistics reported for each projection include: the page size, the number of pages needed to back all four regions, a translation miss score, and a cold translation miss score.

The summary section lists the processes profiled and the statistics reported including: number/percentage of memory reference, modeled memory reference, malloc calls, and free calls.

How to interpret the results

The translation miss score is an indicator of the translation miss rate and ranges from 0 (no translation misses) to 1 (every reference results in a translation miss).

The translation miss rate is defined as:

text
Translation miss rate = (Number of translation misses)/(Number of translation buffer accesses)

The translation miss score differs from the actual translation miss rate because it is based on sampled references. Sampling has the effect of reducing the denominator (Number of translation buffer accesses) in the above equation faster than the numerator (Number of translation misses). As a result, the translation miss score tends to overestimate the actual translation miss rate at increasing sampling rates. Thus, the translation score should be interpreted as a relative measure for comparing the effectiveness of different projections rather than as a predictor of actual translation miss rates.

The translation miss score is directly affected by larger page sizes: growing the page size reduces the translation miss score. The performance projection report includes both a cold translation miss score (such

as compulsory misses) and a total translation miss score (such as compulsory and capacity misses). The cold translation miss score provides a useful lower bound; if growing the page size has reduced the translation miss score to the cold translation miss score, then all capacity translation misses have been eliminated and further increases in page size can only have negligible additional benefits.

The performance projection for a process would appear similar to the following:

text
Modeled region for the process ./workload [661980]

====== ===== ==== ========= ========= heap 0x1100059b0 0x1207b0b60 269996.43 74.45 data 0x110000710 0x11000598c 20.63 1.55 stack 0xffffffffffced10 0xfffffffffffffe0 196.71 20.44 text 0x100000288 0x100053710 333.14 2.56

Performance projection for the process ./workload [661980]

====== ======== ======== ========== ============= heap 4 KB 67500 0.92343 (100.0%) 0.09234 (100.0%) heap 64 KB 4219 0.53615 ( 45.0%) 0.02744 ( 30.0%) heap 16 MB 17 0.00010 ( 00.1%) 0.00002 ( 00.1%) data 4 KB 6 0.53615 (100.0%) 0.02744 (100.0%) data 64 KB 1 0.00053 ( 00.1%) 0.00009 ( 00.1%) data 16 MB 1 0.00053 ( 00.1%) 0.00009 ( 00.1%) stack 4 KB 50 0.53615 (100.0%) 0.02744 (100.0%) stack 64 KB 4 0.05361 ( 10.0%) 0.00274 ( 10.0%) stack 16 MB 1 0.00053 ( 00.1%) 0.00009 ( 00.1%) text 4 KB 84 0.53615 (100.0%) 0.04744 (100.0%) text 64 KB 6 0.05361 ( 10.0%) 0.00274 ( 10.0%) text 16 MB 1 0.00053 ( 00.1%) 0.00009 ( 00.1%)

Data profiling:

The tprof –b command turns on basic data profiling and collects data access information.

The summary section reports access information across kernel data, library data, user global data, and stackheap sections for each process, as shown in the following example:

Table 3. Data profiling of the tprof -b command

Process Freq Total Kernel User Shared Other
tlbref 1 60.49 0.07 59.71 0.38 0.00
/usr/bin/dd 1 39.30 26.75 11.82 0.73 0.00
tprof 2 0.21 0.21 0.00 0.33 0.00
Total 20 100.00 27.03 71.53 1.44 0.00

Table 4. An example of the data profiling report for the /usr/bin/dd process.

tlbref 327688 757943 60.49 0/07 59.71 0.38 0.00 Kernel: 0.04% lib: 0.00% u_global: 0.00% stackheap: u_global: 0.00% unresolved: 99.42% tprof 3278000 792863 0.21 0.21 0.00 0.00 0.00 kernel: 0.20% lib: 0.00% u_global: 0.00% stackheap 0.00% unresolved: 0.01% /usr/bin/dd 323768 974985 39.30 26.75 11.82 0.73 0.00 kernel: 12.86% lib: 0.00% u_global: 7.80% stackheap: 2.42% unresolved: 2.18% Total 100.00 27.03 99.01 1.44 0.00

When used with the-s, -u, -k and -e flags, the tprof command's data profiling reports most-used data structures (exported data symbols) in shared library, binary, kernel and kernel extensions. The -B flag also reports the functions that use data structures.

The second table shown is an example of the data profiling report for the /usr/bin/dd process.. The example report shows that __start data structure is the most used data structure in the /usr/bin/dd process, based on the samples collected. The data structure is a list of functions (right aligned) that use the data structure, reported along with their share and source as shown in the following example:

text
Total % For /usr/bin/dd[323768] (/usr/bin/dd) = 11.69
  • .noconv 11.29 /usr/bin/dd

.main 0.14 /usr/bin/dd .read 0.07 glink.s .setobuf 0.05 /usr/bin/dd .rpipe 0.04 /usr/bin/dd .flsh 0.04 /usr/bin/dd .write 0.04 glink.s .wbuf 0.02 /usr/bin/dd .rbuf 0.02 /usr/bin/dd

  • __start 7.80 /usr/bin/dd

.noconv 6.59 /usr/bin/dd .main 0.14 /usr/bin/dd .read 0.04 glink.s .wbuf 0.02 /usr/bin/dd .write 0.02 glink.s .flsh 0.102 /usr/bin/dd

tprof 명령의 구현

tprof 명령은 시스템 trace 기능을 씁니다. trace 기능은 한 번에 한 사용자만 쓸 수 있으므로 tprof 명령도 한 번에 하나만 실행할 수 있습니다.

tprof 명령의 원래 데이터는 trace 기능으로 얻을 수 있습니다. trace 기능은 Files Reference의 Analyzing Performance with the Trace Facility를 봅니다.

프로그램을 프로파일링하면 trace 기능이 켜지고, 시스템 클록 인터럽트가 일어날 때(프로세서마다 초당 100번) 명령어 주소 레지스터(IAR)의 내용을 기록하는 훅 ID 234의 데이터를 모으도록 지시받습니다. tprof가 프로세스와 디스패치 활동을 추적할 수 있도록 다른 trace 훅도 몇 개 켜집니다. trace 레코드는 디스크 파일에 쓰지 않고 파이프에 씁니다. 파이프를 읽는 프로그램은 만난 프로그램 주소와 각 주소가 나온 횟수의 표를 만듭니다. 프로파일링하는 작업 부하가 끝나면 주소와 횟수의 표를 디스크에 씁니다. 그다음 tprof의 데이터 축약 부분이 만난 명령어 주소를 여러 프로그램이 차지한 주소 범위와 대응시켜, 작업 부하에 관련된 프로그램들에 주소 출현 횟수, 곧 틱이 어떻게 나뉘는지 보고합니다.

틱의 분포는 각 프로그램에서 쓴 CPU 시간에 대략 비례하며, 틱 하나는 10밀리초입니다. 많이 쓰는 프로그램을 알아내면 hot spot을 재구성하거나 사용을 줄이는 조치를 할 수 있습니다.

영어 원문

Implementation of the tprof command

The tprof command uses the system trace facility. Since you can only execute the trace facility one user at a time, you can only execute one tprof command at a time.

You can obtain the raw data for the tprof command through the trace facility. For more information about the trace facility, see Analyzing Performance with the Trace Facility in Files Reference.

When a program is profiled, the trace facility is activated and instructed to collect data from the trace hook with hook ID 234 that records the contents of the Instruction Address Register, or IAR, when a system-clock interrupt occurs (100 times a second per processor). Several other trace hooks are also activated to enable the tprof command to track process and dispatch activity. The trace records are not written to a disk file. They are written to a pipe that is read by a program that builds a table of the unique program addresses that have been encountered and the number of times each one occurred. When the workload being profiled is complete, the table of addresses and their occurrence counts are written to disk. The data-reduction component of the tprof command then correlates the instruction addresses that were encountered with the ranges of addresses occupied by the various programs and reports the distribution of address occurrences, or ticks, across the programs involved in the workload.

The distribution of ticks is roughly proportional to the CPU time spent in each program, which is 10 milliseconds per tick. After the high-use programs are identified, you can take action to restructure the hot spots or minimize their use.

(6.1) tprof 명령의 예

tprof 명령의 자세한 내용은 Files Reference를 봅니다.

다음은 tprof 명령으로 프로그램의 CPU 틱 프로파일을 모으는 예입니다. 4-way SMP 시스템에서 실행했으며 빠른 시스템이라 명령이 1초 안에 끝났습니다. 프로그램을 더 오래 돌리려고 배열 크기 Asize를 1024 대신 4096으로 바꿨습니다.

다음 명령을 실행하면 현재 디렉터리에 version1.prof 파일이 만들어집니다.

text
# tprof -z -u -p version1 -x version1

version1.prof 파일은 version1 프로그램이 실행되는 동안 시스템에서 실행된 각 프로그램이 쓴 CPU 틱 수를 보고합니다.

다음은 version1.prof 파일의 내용 예입니다.

text
         Process            Freq    Total   Kernel     User   Shared    Other
         =======            ====    =====   ======     ====   ======    =====
            wait               4     5810     5810        0        0        0
      ./version1               1     1672       35     1637        0        0
  /usr/bin/tprof               2       15       13        0        2        0
      /etc/syncd               1        2        2        0        0        0
     /usr/bin/sh               2        2        2        0        0        0
         swapper               1        1        1        0        0        0
/usr/bin/trcstop               1        1        1        0        0        0
            rmcd               1        1        1        0        0        0
         =======             ===    =====   ======     ====   ======    =====
           Total              13     7504     5865     1637        2        0
          Process      PID      TID    Total   Kernel     User   Shared    Other
         =======      ===      ===    =====   ======     ====   ======    =====
            wait    16392    16393     1874     1874        0        0        0
            wait    12294    12295     1873     1873        0        0        0
            wait    20490    20491     1860     1860        0        0        0
      ./version1   245974   606263     1672       35     1637        0        0
            wait     8196     8197      203      203        0        0        0
  /usr/bin/tprof   291002   643291       13       13        0        0        0
  /usr/bin/tprof   274580   610467        2        0        0        2        0
      /etc/syncd    73824   110691        2        2        0        0        0
     /usr/bin/sh   245974   606263        1        1        0        0        0
     /usr/bin/sh   245976   606265        1        1        0        0        0
/usr/bin/trcstop   245976   606263        1        1        0        0        0
         swapper        0        3        1        1        0        0        0
          rmcd   155876   348337        1        1        0        0        0
       =======      ===      ===    =====   ======     ====   ======    =====
         Total                       7504     5865     1637        2        0
   Total Samples = 7504       Total Elapsed Time = 18.76s
Profile: ./version1
Total Ticks For All Processes (./version1) = 1637
        Subroutine   Ticks     %        Source   Address  Bytes
     =============  ======  ======     =======   =======  =====
             .main    1637   21.82  version1.c       350    536
Profile: ./version1
Total Ticks For ./version1[245974] (./version1) = 1637
        Subroutine   Ticks     %        Source   Address  Bytes
     =============  ======  ======     =======   =======  =====
             .main    1637   21.82  version1.c       350    536

보고서의 첫 절은 프로세스 ID(PID)와 상관없이 프로그램별로 결과를 요약합니다. 각 프로그램을 실행한 서로 다른 프로세스 수(Freq)를 보여 줍니다.

둘째 절은 각 프로세스가 (또는 그 프로세스를 위해) 쓴 틱 수를 보여 줍니다. 이 예에서 version1 프로그램은 직접 1637틱을 썼고, version1 프로세스를 위해 커널에서 35틱이 일어났습니다.

셋째 절은 프로파일링하는 실행 프로그램의 사용자 틱을 나눠 보여 줍니다. 실행 프로그램의 함수마다 쓴 틱 수와, 그 틱이 실행 전체 CPU 틱(7504)에서 차지하는 백분율을 보고합니다. 시스템의 CPU가 대부분 유휴 상태였으므로 7504틱의 대부분은 유휴 틱입니다.

이 프로그램이 바쁜 시간의 몇 퍼센트를 차지했는지 보려면, 전체에서 wait 스레드의 CPU 틱(유휴 CPU 틱)을 빼고 그 차이로 프로그램의 틱 수를 나눕니다.

text
Total number of ticks / (Total - Idle CPU ticks) = % busy time of program
                1637 /  (7504 - 5810) =
                1637 /  1694 = 0.97

그래서 시스템이 바쁜 틱 가운데 97%입니다.

영어 원문

Example: tprof command

You can view the complete details of the tprof command in Files Reference.

The following example demonstrates how to collect a CPU tick profile of a program using the tprof command. The example was executed on a 4-way SMP system and since it is a fast-running system, the command completed in less than a second. To make this program run longer, the array size, or Asize, was changed to 4096 instead of 1024.

Upon running the following command, the version1.prof file is created in the current directory:

text
# tprof -z -u -p version1 -x version1

The version1.prof file reports how many CPU ticks for each of the programs that were running on the system while the version1 program was running.

The following is an example of what the version1.prof file contains:

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

The first section of the report summarizes the results by program, regardless of the process ID, or PID. It shows the number of different processes, or Freq, that ran each program at some point.

The second section of the report displays the number of ticks consumed by, or on behalf of, each process. In the example, the version1 program used 1637 ticks itself and 35 ticks occurred in the kernel on behalf of the version1 process.

The third section breaks down the user ticks associated with the executable program being profiled. It reports the number of ticks used by each function in the executable program and the percentage of the total run's CPU ticks (7504) that each function's ticks represent. Since the system's CPUs were mostly idle, most of the 7504 ticks are idle ticks.

To see what percentage of the busy time this program took, subtract the wait thread's CPU ticks, which are the idle CPU ticks, from the total and then divide the difference from the total number of ticks.

text
Total number of ticks / (Total - Idle CPU ticks) = % busy time of program
                1637 /  (7504 - 5810) =
                1637 /  1694 = 0.97

So, the percentage of system busy ticks is 97%.

raso 튜닝 매개변수

root 사용자는 raso 명령의 tprof_inst_threshold 매개변수로 명령어 임계값을 조정할 수 있습니다.

root 사용자는 다음 raso 매개변수로 표본 수집 빈도를 조정할 수 있습니다.

  • tprof_cyc_mult
  • tprof_evt_mult

예를 들어 프로세서 사이클 기반 이벤트에서 tprof_cyc_mult를 50으로 설정하고 -f 플래그를 100으로 주면 표본 수집 빈도를 100/50밀리초로 지정한 것과 같습니다.

다른 성능 모니터 이벤트에서는 tprof_evt_mult를 100으로 설정하고 -f 플래그를 20,000으로 주면 표본 수집 빈도를 20,000/100회로 지정한 것과 같습니다.

영어 원문

The raso tunables

As the root user, you can tune the instruction threshold with the tprof_inst_threshold tunable of the raso command.

As the root user, you can tune the sampling frequency with the following raso tunables:

  • tprof_cyc_mult

  • tprof_evt_mult

For example, for events based on processor cycles, setting the tprof_cyc_mult tunable to 50 and specifying the -f flag as 100 is equivalent to specifying a sampling frequency of 100/50 milliseconds.

For other Performance Monitor events, setting the tprof_evt_mult tunable to 100 and specifying the -f flag as 20,000 is equivalent to specifying a sampling frequency of 20,000/100 occurrences.

tprof 명령으로 오프라인 처리하기

tprof 명령으로 trace 파일을 오프라인으로 처리할 수 있지만, 파일 이름을 rootstring 이름으로 지정해야 합니다.

또 tprof 명령이 쓰는 입력 파일에는 정해진 접미사가 필요합니다. 예를 들어 trace 바이너리 파일은 .trc로 끝나야 합니다. gensyms 명령의 출력도 모아 rootstring.syms 파일에 넣어야 합니다.

tprof가 나중에 처리할 수 있을 만큼 trace 파일에 정보가 충분하려면 trace 명령줄에 -M과 -j tprof 플래그가 있어야 합니다.

rootstring 파일 이름을 trace1로 정했다면, 모든 훅을 쓰거나 적어도 다음 훅을 쓰는 trace 명령으로 trace를 모을 수 있습니다.

text
# trace -af -M -T 1000000 -L 10000000 -o trace1.trc -j tprof
# workload
# trcoff
# gensyms > trace1.syms
# trcstop
# trcrpt -r trace1 -k -u -s -z

위 예는 trace1.prof 파일을 만들며, trace 명령이 실행되는 동안 시스템의 CPU 프로파일을 보여 줍니다.

영어 원문

Manual offline processing with the tprof command

You can perform offline processing of trace files with the tprof command, but you must specify filenames with a rootstring name.

Also, there are certain suffixes required for the input files that the tprof command uses. For example, the trace binary file must end in .trc. Also, you need to collect the gensyms command output and put it in a file called the rootstring.syms file.

To insure the trace file contains sufficient information to be post-processed by tprof, the trace command line must include the -M and -j tprof flags.

If you name the rootstring file trace1, to collect a trace, you can use the trace command using all of the hooks or at least the following hooks:

text
# trace -af -M -T 1000000 -L 10000000 -o trace1.trc -j tprof
# workload
# trcoff
# gensyms > trace1.syms
# trcstop
# trcrpt -r trace1 -k -u -s -z

The example above creates a trace1.prof file, which gives you a CPU profile of the system while the trace command was running.

자주 쓰는 형태

bash
timex -s ./myprog                   # 실행 시간과 sar 데이터
cc -pg -o myprog myprog.c && ./myprog && gprof myprog gmon.out > myprog.gprof
tprof -skex sleep 30                # 30초 동안 시스템 전체(공유 라이브러리·커널·커널 확장 포함) -> sleep.prof
tprof -z -u -p myprog -x ./myprog   # 프로그램 하나의 함수별 틱 -> myprog.prof
tprof -E PM_MRK_INST_CMPL -f 50000 -x ./myprog   # 이벤트 기반