溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

【Linux】Perf工具詳解

發(fā)布時間:2020-08-07 10:03:23 來源:ITPUB博客 閱讀:238 作者:小亮520cl 欄目:建站服務(wù)器

原文地址:http://blog.csdn.net/zhangskd/article/details/37902159
從2.6.31內(nèi)核開始,linux內(nèi)核自帶了一個性能分析工具perf,能夠進行函數(shù)級與指令級的熱點查找。

 

perf

 

Performance analysis tools for Linux.

Performance counters for Linux are a new kernel-based subsystem that provide a framework for all things

performance analysis. It covers hardware level (CPU/PMU, Performance Monitoring Unit) features and

software features (software counters, tracepoints) as well.

 

Perf是內(nèi)置于Linux內(nèi)核源碼樹中的性能剖析(profiling)工具。

它基于事件采樣原理,以性能事件為基礎(chǔ),支持針對處理器相關(guān)性能指標與操作系統(tǒng)相關(guān)性能指標的性能剖析。

常用于性能瓶頸的查找與熱點代碼的定位。

 

CPU周期(cpu-cycles)是默認的性能事件,所謂的CPU周期是指CPU所能識別的最小時間單元,通常為億分之幾秒,

是CPU執(zhí)行最簡單的指令時所需要的時間,例如讀取寄存器中的內(nèi)容,也叫做clock tick。

 

Perf是一個包含22種子工具的工具集,以下是最常用的5種:

perf-list

perf-stat

perf-top

perf-record

perf-report

 

perf-list

 

Perf-list用來查看perf所支持的性能事件,有軟件的也有硬件的。

 

List all symbolic event types.

perf list [hw | sw | cache | tracepoint | event_glob]

 

(1) 性能事件的分布

hw:Hardware event,9個

sw:Software event,9個

cache:Hardware cache event,26個

tracepoint:Tracepoint event,775個

 

sw實際上是內(nèi)核的計數(shù)器,與硬件無關(guān)。

hw和cache是CPU架構(gòu)相關(guān)的,依賴于具體硬件。

tracepoint是基于內(nèi)核的ftrace,主線2.6.3x以上的內(nèi)核版本才支持。

 

(2) 指定性能事件(以它的屬性)

-e <event> : u // userspace

-e <event> : k // kernel

-e <event> : h // hypervisor

-e <event> : G // guest counting (in KVM guests)

-e <event> : H // host counting (not in KVM guests)

 

(3) 使用例子

顯示內(nèi)核和模塊中,消耗最多CPU周期的函數(shù):

# perf top -e cycles:k

顯示分配高速緩存最多的函數(shù):

# perf top -e kmem:kmem_cache_alloc

 

perf-top

 

對于一個指定的性能事件(默認是CPU周期),顯示消耗最多的函數(shù)或指令。

 

System profiling tool.

Generates and displays a performance counter profile in real time.

perf top [-e <EVENT> | --event=EVENT] [<options>]

 

perf top主要用于實時分析各個函數(shù)在某個性能事件上的熱度,能夠快速的定位熱點函數(shù),包括應(yīng)用程序函數(shù)、

模塊函數(shù)與內(nèi)核函數(shù),甚至能夠定位到熱點指令。默認的性能事件為cpu cycles。

 

(1) 輸出格式

# perf top

[plain] view plain copy
 【Linux】Perf工具詳解
  1. Samples: 1M of event 'cycles', Event count (approx.): 73891391490  
  2.      5.44%  perf              [.] 0x0000000000023256        
  3.      4.86%  [kernel]          [k] _spin_lock                
  4.      2.43%  [kernel]          [k] _spin_lock_bh             
  5.      2.29%  [kernel]          [k] _spin_lock_irqsave        
  6.      1.77%  [kernel]          [k] __d_lookup                
  7.      1.55%  libc-2.12.so      [.] __strcmp_sse42            
  8.      1.43%  nginx             [.] ngx_vslprintf             
  9.      1.37%  [kernel]          [k] tcp_poll            

第一列:符號引發(fā)的性能事件的比例,默認指占用的cpu周期比例。

第二列:符號所在的DSO(Dynamic Shared Object),可以是應(yīng)用程序、內(nèi)核、動態(tài)鏈接庫、模塊。

第三列:DSO的類型。[.]表示此符號屬于用戶態(tài)的ELF文件,包括可執(zhí)行文件與動態(tài)鏈接庫)。[k]表述此符號屬于內(nèi)核或模塊。

第四列:符號名。有些符號不能解析為函數(shù)名,只能用地址表示。

 

(2) 常用交互命令

h:顯示幫助

UP/DOWN/PGUP/PGDN/SPACE:上下和翻頁。

a:annotate current symbol,注解當前符號。能夠給出匯編語言的注解,給出各條指令的采樣率。

d:過濾掉所有不屬于此DSO的符號。非常方便查看同一類別的符號。

P:將當前信息保存到perf.hist.N中。

 

(3) 常用命令行參數(shù)

-e <event>:指明要分析的性能事件。

-p <pid>:Profile events on existing Process ID (comma sperated list). 僅分析目標進程及其創(chuàng)建的線程。

-k <path>:Path to vmlinux. Required for annotation functionality. 帶符號表的內(nèi)核映像所在的路徑。

-K:不顯示屬于內(nèi)核或模塊的符號。

-U:不顯示屬于用戶態(tài)程序的符號。

-d <n>:界面的刷新周期,默認為2s,因為perf top默認每2s從mmap的內(nèi)存區(qū)域讀取一次性能數(shù)據(jù)。

-G:得到函數(shù)的調(diào)用關(guān)系圖。

perf top -G [fractal],路徑概率為相對值,加起來為100%,調(diào)用順序為從下往上。

perf top -G graph,路徑概率為絕對值,加起來為該函數(shù)的熱度。

 

(4) 使用例子

# perf top // 默認配置

# perf top -G // 得到調(diào)用關(guān)系圖

# perf top -e cycles // 指定性能事件

# perf top -p 23015,32476 // 查看這兩個進程的cpu cycles使用情況

# perf top -s comm,pid,symbol // 顯示調(diào)用symbol的進程名和進程號

# perf top --comms nginx,top // 僅顯示屬于指定進程的符號

# perf top --symbols kfree // 僅顯示指定的符號

 

perf-stat

 

用于分析指定程序的性能概況。

 

Run a command and gather performance counter statistics.

perf stat [-e <EVENT> | --event=EVENT] [-a] <command>

perf stat [-e <EVENT> | --event=EVENT] [-a] - <command> [<options>]

 

(1) 輸出格式

# perf stat ls

[plain] view plain copy
 【Linux】Perf工具詳解
  1. Performance counter stats for 'ls':  
  2.   
  3.          0.653782 task-clock                #    0.691 CPUs utilized            
  4.                 0 context-switches          #    0.000 K/sec                    
  5.                 0 CPU-migrations            #    0.000 K/sec                    
  6.               247 page-faults               #    0.378 M/sec                    
  7.         1,625,426 cycles                    #    2.486 GHz                      
  8.         1,050,293 stalled-cycles-frontend   #   64.62% frontend cycles idle     
  9.           838,781 stalled-cycles-backend    #   51.60% backend  cycles idle     
  10.         1,055,735 instructions              #    0.65  insns per cycle          
  11.                                             #    0.99  stalled cycles per insn  
  12.           210,587 branches                  #  322.106 M/sec                    
  13.            10,809 branch-misses             #    5.13% of all branches          
  14.   
  15.       0.000945883 seconds time elapsed  

 

輸出包括ls的執(zhí)行時間,以及10個性能事件的統(tǒng)計。

task-clock:任務(wù)真正占用的處理器時間,單位為ms。CPUs utilized = task-clock / time elapsed,CPU的占用率。

context-switches:上下文的切換次數(shù)。

CPU-migrations:處理器遷移次數(shù)。Linux為了維持多個處理器的負載均衡,在特定條件下會將某個任務(wù)從一個CPU

遷移到另一個CPU。

page-faults:缺頁異常的次數(shù)。當應(yīng)用程序請求的頁面尚未建立、請求的頁面不在內(nèi)存中,或者請求的頁面雖然在內(nèi)

存中,但物理地址和虛擬地址的映射關(guān)系尚未建立時,都會觸發(fā)一次缺頁異常。另外TLB不命中,頁面訪問權(quán)限不匹配

等情況也會觸發(fā)缺頁異常。

cycles:消耗的處理器周期數(shù)。如果把被ls使用的cpu cycles看成是一個處理器的,那么它的主頻為2.486GHz。

可以用cycles / task-clock算出。

stalled-cycles-frontend:略過。

stalled-cycles-backend:略過。

instructions:執(zhí)行了多少條指令。IPC為平均每個cpu cycle執(zhí)行了多少條指令。

branches:遇到的分支指令數(shù)。branch-misses是預(yù)測錯誤的分支指令數(shù)。

 

(2) 常用參數(shù)

-p:stat events on existing process id (comma separated list). 僅分析目標進程及其創(chuàng)建的線程。

-a:system-wide collection from all CPUs. 從所有CPU上收集性能數(shù)據(jù)。

-r:repeat command and print average + stddev (max: 100). 重復(fù)執(zhí)行命令求平均。

-C:Count only on the list of CPUs provided (comma separated list), 從指定CPU上收集性能數(shù)據(jù)。

-v:be more verbose (show counter open errors, etc), 顯示更多性能數(shù)據(jù)。

-n:null run - don't start any counters,只顯示任務(wù)的執(zhí)行時間 。

-x SEP:指定輸出列的分隔符。

-o file:指定輸出文件,--append指定追加模式。

--pre <cmd>:執(zhí)行目標程序前先執(zhí)行的程序。

--post <cmd>:執(zhí)行目標程序后再執(zhí)行的程序。

 

(3) 使用例子

執(zhí)行10次程序,給出標準偏差與期望的比值:

# perf stat -r 10 ls > /dev/null

顯示更詳細的信息:

# perf stat -v ls > /dev/null

只顯示任務(wù)執(zhí)行時間,不顯示性能計數(shù)器:

# perf stat -n ls > /dev/null

單獨給出每個CPU上的信息:

# perf stat -a -A ls > /dev/null

ls命令執(zhí)行了多少次系統(tǒng)調(diào)用:

# perf stat -e syscalls:sys_enter ls 

 

perf-record

 

收集采樣信息,并將其記錄在數(shù)據(jù)文件中。

隨后可以通過其它工具(perf-report)對數(shù)據(jù)文件進行分析,結(jié)果類似于perf-top的。

 

Run a command and record its profile into perf.data.

This command runs a command and gathers a performance counter profile from it, into perf.data,

without displaying anything. This file can then be inspected later on, using perf report.

 

(1) 常用參數(shù)

-e:Select the PMU event.

-a:System-wide collection from all CPUs.

-p:Record events on existing process ID (comma separated list).

-A:Append to the output file to do incremental profiling.

 -f:Overwrite existing data file.

-o:Output file name.

-g:Do call-graph (stack chain/backtrace) recording.

-C:Collect samples only on the list of CPUs provided.

 

(2) 使用例子

記錄nginx進程的性能數(shù)據(jù):

# perf record -p `pgrep -d ',' nginx`

記錄執(zhí)行l(wèi)s時的性能數(shù)據(jù):

# perf record ls -g

記錄執(zhí)行l(wèi)s時的系統(tǒng)調(diào)用,可以知道哪些系統(tǒng)調(diào)用最頻繁:

# perf record -e syscalls:sys_enter ls

 

perf-report

 

讀取perf record創(chuàng)建的數(shù)據(jù)文件,并給出熱點分析結(jié)果。

 

Read perf.data (created by perf record) and display the profile.

This command displays the performance counter profile information recorded via perf record.

 

(1) 常用參數(shù)

-i:Input file name. (default: perf.data)

 

(2) 使用例子

# perf report -i perf.data.2

 

More

 

除了以上5個常用工具外,還有一些適用于較特殊場景的工具, 比如內(nèi)核鎖、slab分配器、調(diào)度器,

也支持自定義探測點。

 

perf-lock

 

內(nèi)核鎖的性能分析。

Analyze lock events.

perf lock {record | report | script | info}

 

需要編譯選項的支持:CONFIG_LOCKDEP、CONFIG_LOCK_STAT。

CONFIG_LOCKDEP defines acquired and release events.

CONFIG_LOCK_STAT defines contended and acquired lock events.

 

(1) 常用選項

-i <file>:輸入文件

-k <value>:sorting key,默認為acquired,還可以按contended、wait_total、wait_max和wait_min來排序。

 

(2) 使用例子

# perf lock record ls // 記錄

# perf lock report // 報告

 

(3) 輸出格式

[plain] view plain copy
 【Linux】Perf工具詳解
  1.                Name   acquired  contended total wait (ns)   max wait (ns)   min wait (ns)   
  2.   
  3. &mm->page_table_...        382          0               0               0               0   
  4. &mm->page_table_...         72          0               0               0               0   
  5.           &fs->lock         64          0               0               0               0   
  6.         dcache_lock         62          0               0               0               0   
  7.       vfsmount_lock         43          0               0               0               0   
  8. &newf->file_lock...         41          0               0               0               0   

 

Name:內(nèi)核鎖的名字。

aquired:該鎖被直接獲得的次數(shù),因為沒有其它內(nèi)核路徑占用該鎖,此時不用等待。

contended:該鎖等待后獲得的次數(shù),此時被其它內(nèi)核路徑占用,需要等待。

total wait:為了獲得該鎖,總共的等待時間。

max wait:為了獲得該鎖,最大的等待時間。

min wait:為了獲得該鎖,最小的等待時間。

最后還有一個Summary:

[plain] view plain copy
 【Linux】Perf工具詳解
  1. === output for debug===  
  2.   
  3. bad: 10, total: 246  
  4. bad rate: 4.065041 %  
  5. histogram of events caused bad sequence  
  6.     acquire: 0  
  7.    acquired: 0  
  8.   contended: 0  
  9.     release: 10  

 

perf-kmem

 

slab分配器的性能分析。

Tool to trace/measure kernel memory(slab) properties.

perf kmem {record | stat} [<options>]

 

(1) 常用選項

--i <file>:輸入文件

--caller:show per-callsite statistics,顯示內(nèi)核中調(diào)用kmalloc和kfree的地方。

--alloc:show per-allocation statistics,顯示分配的內(nèi)存地址。

-l <num>:print n lines only,只顯示num行。

-s <key[,key2...]>:sort the output (default: frag,hit,bytes)

 

(2) 使用例子

# perf kmem record ls // 記錄

# perf kmem stat --caller --alloc -l 20 // 報告

 

(3) 輸出格式

[plain] view plain copy
 【Linux】Perf工具詳解
  1. ------------------------------------------------------------------------------------------------------  
  2.  Callsite                           | Total_alloc/Per | Total_req/Per   | Hit      | Ping-pong | Frag  
  3. ------------------------------------------------------------------------------------------------------  
  4.  perf_event_mmap+ec                 |    311296/8192  |    155952/4104  |       38 |        0 | 49.902%  
  5.  proc_reg_open+41                   |        64/64    |        40/40    |        1 |        0 | 37.500%  
  6.  __kmalloc_node+4d                  |      1024/1024  |       664/664   |        1 |        0 | 35.156%  
  7.  ext3_readdir+5bd                   |        64/64    |        48/48    |        1 |        0 | 25.000%  
  8.  load_elf_binary+8ec                |       512/512   |       392/392   |        1 |        0 | 23.438%  


Callsite:內(nèi)核代碼中調(diào)用kmalloc和kfree的地方。

Total_alloc/Per:總共分配的內(nèi)存大小,平均每次分配的內(nèi)存大小。

Total_req/Per:總共請求的內(nèi)存大小,平均每次請求的內(nèi)存大小。

Hit:調(diào)用的次數(shù)。

Ping-pong:kmalloc和kfree不被同一個CPU執(zhí)行時的次數(shù),這會導(dǎo)致cache效率降低。

Frag:碎片所占的百分比,碎片 = 分配的內(nèi)存 - 請求的內(nèi)存,這部分是浪費的。

有使用--alloc選項,還會看到Alloc Ptr,即所分配內(nèi)存的地址。

最后還有一個Summary:

[plain] view plain copy
 【Linux】Perf工具詳解
  1. SUMMARY  
  2. =======  
  3. Total bytes requested: 290544  
  4. Total bytes allocated: 447016  
  5. Total bytes wasted on internal fragmentation: 156472  
  6. Internal fragmentation: 35.003669%  
  7. Cross CPU allocations: 2/509  

 

probe-sched

 

調(diào)度模塊分析。

trace/measure scheduler properties (latencies)

perf sched {record | latency | map | replay | script}

 

(1) 使用例子 

# perf sched record sleep 10 // perf sched record <command>

# perf report latency --sort max

 

(2) 輸出格式

[plain] view plain copy
 【Linux】Perf工具詳解
  1. ---------------------------------------------------------------------------------------------------------------  
  2.  Task                  |   Runtime ms  | Switches | Average delay ms | Maximum delay ms | Maximum delay at     |  
  3. ---------------------------------------------------------------------------------------------------------------  
  4.  events/10:61          |      0.655 ms |       10 | avg:    0.045 ms | max:    0.161 ms | max at: 9804.958730 s  
  5.  sleep:11156           |      2.263 ms |        4 | avg:    0.052 ms | max:    0.118 ms | max at: 9804.865552 s  
  6.  edac-poller:1125      |      0.598 ms |       10 | avg:    0.042 ms | max:    0.113 ms | max at: 9804.958698 s  
  7.  events/2:53           |      0.676 ms |       10 | avg:    0.037 ms | max:    0.102 ms | max at: 9814.751605 s  
  8.  perf:11155            |      2.109 ms |        1 | avg:    0.068 ms | max:    0.068 ms | max at: 9814.867918 s  


TASK:進程名和pid。

Runtime:實際的運行時間。

Switches:進程切換的次數(shù)。

Average delay:平均的調(diào)度延遲。

Maximum delay:最大的調(diào)度延遲。

Maximum delay at:最大調(diào)度延遲發(fā)生的時刻。

 

perf-probe

 

可以自定義探測點。

Define new dynamic tracepoints.

 

使用例子

(1) Display which lines in schedule() can be probed

# perf probe --line schedule

前面有行號的可以探測,沒有行號的就不行了。

 

(2) Add a probe on schedule() function 12th line.

# perf probe -a schedule:12

在schedule函數(shù)的12處增加一個探測點。

 

Reference

 

[1]. Linux的系統(tǒng)級性能剖析工具系列,by 承剛

[2]. http://www.ibm.com/developerworks/cn/linux/l-cn-perf1/

[3]. http://www.ibm.com/developerworks/cn/linux/l-cn-perf2/

[4]. https://perf.wiki.kernel.org/index.php/Tutorial

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI