이것은 많은 프로파일러의 출력을 도트 그래프로 변환하는 Python 스크립트입니다.
다음을 수행할 수 있습니다.
gprof2dot 에 의해 생성된 그래프에 대한 대화형 뷰어를 원한다면 xdot.py를 확인하세요.
gprof2dot는 현재 내 요구 사항을 충족하고 있으며 유지 관리할 시간이 거의 또는 전혀 없습니다. 따라서 요청한 기능이 구현될 가능성이 거의 없으며 문제 보고서나 풀 요청 처리가 느려질 수도 있습니다.
이는 기본 설정을 사용한 Linux Gazette 기사의 예제 데이터에서 얻은 결과입니다.
Debian/Ubuntu에서는 다음을 실행합니다.
apt-get install python3 graphviz
RedHat/Fedora 실행 시
yum install python3 graphviz
PyPI
pip install gprof2dot
독립형 스크립트
힘내 저장소
Usage:
gprof2dot.py [options] [file] ...
Options:
-h, --help show this help message and exit
-o FILE, --output=FILE
output filename [stdout]
-n PERCENTAGE, --node-thres=PERCENTAGE
eliminate nodes below this threshold [default: 0.5]
-e PERCENTAGE, --edge-thres=PERCENTAGE
eliminate edges below this threshold [default: 0.1]
-f FORMAT, --format=FORMAT
profile format: axe, callgrind, collapse, dtrace,
hprof, json, oprofile, perf, prof, pstats, sleepy,
sysprof or xperf [default: prof]
--total=TOTALMETHOD preferred method of calculating total time: callratios
or callstacks (currently affects only perf format)
[default: callratios]
-c THEME, --colormap=THEME
color map: bw, color, gray, pink or print [default:
color]
-s, --strip strip function parameters, template parameters, and
const modifiers from demangled C++ function names
--color-nodes-by-selftime
color nodes by self time, rather than by total time
(sum of self and descendants)
-w, --wrap wrap function names
--show-samples show function samples
--node-label=MEASURE measurements to on show the node (can be specified
multiple times): self-time, self-time-percentage,
total-time or total-time-percentage [default: total-
time-percentage, self-time-percentage]
--list-functions=LIST_FUNCTIONS
list functions available for selection in -z or -l,
requires selector argument ( use '+' to select all).
Recall that the selector argument is used with
Unix/Bash globbing/pattern matching, and that entries
are formatted '<pkg>:<linenum>:<function>'. When
argument starts with '%', a dump of all available
information is performed for selected entries, after
removal of leading '%'.
-z ROOT, --root=ROOT prune call graph to show only descendants of specified
root function
-l LEAF, --leaf=LEAF prune call graph to show only ancestors of specified
leaf function
--depth=DEPTH prune call graph to show only descendants or ancestors
until specified depth
--skew=THEME_SKEW skew the colorization curve. Values < 1.0 give more
variety to lower percentages. Values > 1.0 give less
variety to lower percentages
-p FILTER_PATHS, --path=FILTER_PATHS
Filter all modules not in a specified path
--compare Compare two graphs with almost identical structure. With this
option two files should be provided.gprof2dot.py
[options] --compare [file1] [file2] ...
--compare-tolerance=TOLERANCE
Tolerance threshold for node difference
(default=0.001%).If the difference is below this value
the nodes are considered identical.
--compare-only-slower
Display comparison only for function which are slower
in second graph.
--compare-only-faster
Display comparison only for function which are faster
in second graph.
--compare-color-by-difference
Color nodes based on the value of the difference.
Nodes with the largest differences represent the hot
spots.
perf record -g -- /path/to/your/executable
perf script | c++filt | gprof2dot.py -f perf | dot -Tpng -o output.png
opcontrol --callgraph=16
opcontrol --start
/path/to/your/executable arg1 arg2
opcontrol --stop
opcontrol --dump
opreport -cgf | gprof2dot.py -f oprofile | dot -Tpng -o output.png
xperf에 익숙하지 않다면 먼저 이 훌륭한 기사를 읽어 보십시오. 그런 다음 다음을 수행하십시오.
다음으로 xperf를 시작하세요.
xperf -on Latency -stackwalk profile
애플리케이션을 실행하세요.
데이터를 저장합니다. ` xperf -d 출력.etl
시각화 도우미를 시작합니다.
xperf output.etl
추적 메뉴에서 기호 로드를 선택합니다. 필요한 경우 기호 경로를 구성합니다 .
CPU 샘플링 그래프 에서 관심 영역을 선택하고 마우스 오른쪽 버튼을 클릭한 후 요약 테이블 을 선택합니다.
열 메뉴에서 스택 열이 활성화되어 있고 표시되는지 확인하세요.
행을 마우스 오른쪽 버튼으로 클릭하고 전체 테이블 내보내기를 선택한 다음 output.csv 에 저장합니다.
그런 다음 gprof2dot를 다음과 같이 호출하십시오.
gprof2dot.py -f xperf output.csv | dot -Tpng -o output.png
다음과 같이 프로필 데이터를 수집합니다(GUI에서도 수행 가능).
amplxe-cl -collect hotspots -result-dir output -- your-app
프로필 데이터를 다음과 같이 시각화합니다.
amplxe-cl -report gprof-cc -result-dir output -format text -report-output output.txt
gprof2dot.py -f axe output.txt | dot -Tpng -o output.png
Kirill Rogozhin의 블로그 게시물도 참조하세요.
/path/to/your/executable arg1 arg2
gprof path/to/your/executable | gprof2dot.py | dot -Tpng -o output.png
python -m profile -o output.pstats path/to/your/script arg1 arg2
gprof2dot.py -f pstats output.pstats | dot -Tpng -o output.png
python -m cProfile -o output.pstats path/to/your/script arg1 arg2
gprof2dot.py -f pstats output.pstats | dot -Tpng -o output.png
java -agentlib:hprof=cpu=samples ...
gprof2dot.py -f hprof java.hprof.txt | dot -Tpng -o output.png
자세한 내용은 Russell Power의 블로그 게시물을 참조하세요.
dtrace -x ustackframes=100 -n 'profile-97 /pid == 12345/ { @[ustack()] = count(); } tick-60s { exit(0); }' -o out.user_stacks
gprof2dot.py -f dtrace out.user_stacks | dot -Tpng -o output.png
# Notice: sometimes, the dtrace outputs format may be latin-1, and gprof2dot will fail to parse it.
# To solve this problem, you should use iconv to convert to UTF-8 explicitly.
# TODO: add an encoding flag to tell gprof2dot how to decode the profile file.
iconv -f ISO-8859-1 -t UTF-8 out.user_stacks | gprof2dot.py -f dtrace
Brendan Gregg의 FlameGraph 도구는 샘플당 한 줄이 포함된 텍스트 파일을 입력으로 사용합니다. 이 형식은 FlameGraph 저장소의 stackcollapse
스크립트를 사용하여 다양한 다른 입력에서 생성될 수 있습니다. py-spy와 같은 도구를 사용하여 생성할 수도 있습니다.
사용 예:
성능
perf record -g -- /path/to/your/executable
perf script | FlameGraph/stackcollapse-perf.pl > out.collapse
gprof2dot.py -f collapse out.collapse | dot -Tpng -o output.png
파이스파이
py-spy record -p <pidfile> -f raw -o out.collapse
gprof2dot.py -f collapse out.collapse | dot -Tpng -o output.png
이 이미지는 --compare
및 --compare-color-by-difference
옵션의 사용 예를 보여줍니다.
오른쪽을 가리키는 화살표는 두 번째 프로파일(두 번째 프로파일)로 제공된 프로파일에서 기능이 더 빠르게 수행된 노드를 나타내고, 왼쪽을 가리키는 화살표는 첫 번째 프로파일(첫 번째 프로파일)로 제공된 프로파일에서 기능이 더 빠르게 수행된 노드를 나타냅니다. .
+-----------------------------+
| function name
| total time % -/+ total_diff
| ( self time % ) -/+ self_diff /
| total calls1 / total calls2 /
+-----------------------------+
어디
total time %
및 self time %
첫 번째 프로필에서 가져옵니다.diff
는 time in the first profile - time in the second profile
의 절대값으로 계산됩니다.참고 비교 옵션은 pstats, ax 및 callgrind 프로필에 대해 테스트되었습니다.
출력 그래프의 노드는 함수를 나타내며 다음과 같은 레이아웃을 갖습니다.
+------------------------------+
| function name |
| total time % ( self time % ) |
| total calls |
+------------------------------+
어디:
에지는 두 함수 간의 호출을 나타내며 다음과 같은 레이아웃을 갖습니다.
total time %
calls
parent --------------------> children
어디:
재귀 주기에서 노드의 총 시간 %는 주기의 전체 함수에 대해 동일하며, 주기 내부 가장자리에는 총 시간 % 수치가 없습니다. 이러한 수치는 의미가 없기 때문입니다.
노드와 엣지의 색상은 총 시간 % 값에 따라 달라집니다. 기본 온도 유사 컬러맵에서 가장 많은 시간이 소요되는 기능(핫스팟)은 진한 빨간색으로 표시되고, 시간이 거의 소요되지 않는 기능은 진한 파란색으로 표시됩니다. 시간이 거의 소요되지 않거나 시간이 전혀 소요되지 않는 기능은 기본적으로 그래프에 표시되지 않습니다.
--list-functions
플래그를 사용하면 gprof
입력에서 발견된 함수 항목을 나열할 수 있습니다. 이는 --leaf
( -l
) 또는 --root
( -z
) 플래그를 사용하여 활용을 준비하는 도구로 사용됩니다.
prof2dot.py -f pstats /tmp/myLog.profile --list-functions "test_segments:*:*"
test_segments:5:<module>,
test_segments:206:TestSegments,
test_segments:46:<lambda>
선택기 인수는 -l
및 -z
플래그에서 수행되는 것과 동일한 방식으로 Unix/Bash 글로빙/패턴 일치와 함께 사용됩니다.
항목 형식은 '<pkg>:<linenum>:<function>'입니다.
선택기 인수가 '%'로 시작하면 선택기 앞의 '%'를 제거한 후 선택한 항목에 대해 사용 가능한 모든 정보 덤프가 수행됩니다. 선택기가 "+" 또는 "*"인 경우 전체 기능 목록이 인쇄됩니다.
기본적으로 gprof2dot.py
총 계산 시간에 거의 또는 전혀 영향을 주지 않고 노드와 가장자리를 제외하고 부분 호출 그래프를 생성합니다. 전체 호출 그래프를 원할 경우 다음과 같이 -n
/ --node-thres
및 -e
/ --edge-thres
옵션을 통해 노드 및 에지에 대한 임계값을 0으로 설정합니다.
gprof2dot.py -n0 -e0
demangled C++ 함수 이름에 범위, 함수 인수 및 템플릿 인수가 포함되어 있기 때문에 C++ 코드를 프로파일링할 때 노드 레이블이 매우 넓어질 수 있습니다.
함수 및 템플릿 인수 정보가 필요하지 않은 경우 -s
/ --strip
옵션을 전달하여 제거합니다.
해당 정보를 모두 유지하고 싶거나 레이블이 여전히 너무 넓은 경우 -w
/ --wrap
전달하여 레이블을 래핑할 수 있습니다. dot
라벨을 자동으로 감싸지 않기 때문에 라벨 여백이 완벽하게 정렬되지는 않습니다.
아마도 총 실행 시간이 너무 짧기 때문에 시간이 소요되는 위치를 판단하기 위한 프로필의 정밀도가 충분하지 않습니다.
다음과 같이 -n
/ --node-thres
및 -e
/ --edge-thres
옵션을 통해 노드 및 에지의 임계값을 0으로 설정하여 전체 그래프를 강제로 표시할 수 있습니다.
gprof2dot.py -n0 -e0
그러나 의미 있는 결과를 얻으려면 더 오랜 기간 동안 프로그램을 실행하는 방법을 찾아야 합니다(여러 실행에서 결과를 집계).
실행 시간이 너무 짧아서 반올림 오류가 커질 수 있습니다.
실행 시간을 늘리는 방법은 위의 질문을 참조하세요.
적합한 결과를 생성하는 데 필수적인 옵션은 다음과 같습니다.
-g
: 디버깅 정보 생성-fno-omit-frame-pointer
: 프레임 포인터를 사용합니다(x86_64와 같은 일부 아키텍처 및 일부 최적화 수준에서는 프레임 포인터 사용이 기본적으로 비활성화되어 있습니다. 프레임 포인터 없이는 호출 스택을 탐색하는 것이 불가능합니다) gprof를 사용하는 경우 -pg
옵션도 필요하지만 요즘에는 다른 프로파일링 도구를 사용하여 훨씬 더 나은 결과를 얻을 수 있습니다. 대부분의 도구는 컴파일할 때 특별한 코드 도구가 필요하지 않습니다.
프로파일링하는 코드가 출시할 코드와 최대한 유사하기를 원합니다. 따라서 릴리스 코드에 사용하는 모든 옵션을 포함 해야 합니다 . 일반적으로 다음과 같습니다.
-O2
: 공간-속도 트레이드오프를 포함하지 않는 최적화-DNDEBUG
: 표준 라이브러리의 디버깅 코드(예: 어설션 매크로)를 비활성화합니다.그러나 gcc에서 수행되는 많은 최적화는 프로파일링 결과의 정확성/세분성을 방해합니다. 특정 최적화를 비활성화하려면 다음 옵션을 전달 해야 합니다 .
-fno-inline-functions
: 함수를 상위 항목에 인라인하지 않습니다(그렇지 않으면 이 함수에 소요된 시간이 호출자에게 귀속됩니다).-fno-inline-functions-called-once
: 위와 유사-fno-optimize-sibling-calls
: 형제 및 꼬리 재귀 호출을 최적화하지 않습니다(그렇지 않으면 꼬리 호출이 상위 함수에 기인할 수 있음)세분성이 여전히 너무 낮은 경우 다음 옵션을 전달하여 더 세밀한 세분성을 얻을 수 있습니다.
-fno-default-inline
: 단지 클래스 범위 내에 정의되어 있다는 이유만으로 멤버 함수를 기본적으로 인라인으로 만들지 마세요.-fno-inline
: inline 키워드에 주의하지 마세요. 그러나 이 마지막 옵션을 사용하면 함수 호출 오버헤드로 인해 여러 번 호출되는 함수의 타이밍이 왜곡될 수 있습니다. 이는 적절한 성능을 위해 이러한 최적화가 수행될 것으로 기대하는 일반적인 C++ 코드의 경우 특히 그렇습니다.자세한 내용은 gcc 최적화 옵션의 전체 목록을 참조하세요.
보완/대체 도구를 포함한 외부 리소스는 위키를 참조하세요.