系統級效能分析工具 — Perf

來源:互聯網
上載者:User

標籤:

離2.6.31核心開始。linux核心配備了效能分析工具perf,它可以是功能級和指令級熱外表。

 

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是內建於Linux核心原始碼樹中的效能剖析(profiling)工具。

它基於事件採樣原理。以效能事件為基礎,支援針對處理器相關效能指標與作業系統相關效能指標的效能剖析。

經常使用於效能瓶頸的尋找與熱點代碼的定位。

 

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

是CPU運行最簡單的指令時所須要的時間,比如讀取寄存器中的內容,也叫做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實際上是核心的計數器,與硬體無關。

hw和cache是CPU架構相關的,依賴於詳細硬體。

tracepoint是基於核心的ftrace,主線2.6.3x以上的核心版本號碼才支援。

 

(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) 使用範例

顯示核心和模組中。消耗最多CPU周期的函數:

# perf top -e cycles:k

顯示分配快速緩衝最多的函數:

# perf top -e kmem:kmem_cache_alloc

 

perf-top

 

對於一個指定的效能事件(預設是CPU周期),顯示消耗最多的函數或指令。

 

System profiling tool.

Generates and displays a performance counter profile in real time.

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

 

perf top主要用於即時分析各個函數在某個效能事件上的熱度,可以高速的定位熱點函數。包含應用程式函數、

模組函數與核心功能,甚至可以定位到熱點指令。預設的效能事件為cpu cycles。

 

(1) 輸出格式

# perf top

Samples: 1M of event 'cycles', Event count (approx.): 73891391490     5.44%  perf              [.] 0x0000000000023256           4.86%  [kernel]          [k] _spin_lock                   2.43%  [kernel]          [k] _spin_lock_bh                2.29%  [kernel]          [k] _spin_lock_irqsave           1.77%  [kernel]          [k] __d_lookup                   1.55%  libc-2.12.so      [.] __strcmp_sse42               1.43%  nginx             [.] ngx_vslprintf                1.37%  [kernel]          [k] tcp_poll          

第一列:符號引發的效能事件的比例,預設指佔用的cpu周期比例。

第二列:符號所在的DSO(Dynamic Shared Object),能夠是應用程式、核心、動態連結程式庫、模組。

第三列:DSO的類型。[.]表示此符號屬於使用者態的ELF檔案,包含可運行檔案與動態連結程式庫)。[k]表述此符號屬於核心或模組。

第四列:符號名。

有些符號不能解析為函數名。僅僅能用地址表示。

 

(2) 經常使用互動命令

h:顯示協助

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

a:annotate current symbol。註解當前符號。可以給出組合語言的註解。給出各條指令的採樣率。

d:過濾掉全部不屬於此DSO的符號。

很方便查看同一類別的符號。

P:將當前資訊儲存到perf.hist.N中。

 

(3) 經常使用命令列參數

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

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

-k <path>:Path to vmlinux. Required for annotation functionality. 帶符號表的核心映像所在的路徑。

-K:不顯示屬於核心或模組的符號。

-U:不顯示屬於使用者態程式的符號。

-d <n>:介面的重新整理周期。默覺得2s,由於perf top預設每2s從mmap的記憶體地區讀取一次效能資料。

-G:得到函數的呼叫歷程圖。

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

perf top -G graph,路徑機率為絕對值,加起來為該函數的熱度。

 

(4) 使用範例

# perf top // 預設配置

# perf top -G // 得到呼叫歷程圖

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

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

# perf top -s comm,pid,symbol // 顯示調用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

 Performance counter stats for 'ls':          0.653782 task-clock                #    0.691 CPUs utilized                           0 context-switches          #    0.000 K/sec                                   0 CPU-migrations            #    0.000 K/sec                                 247 page-faults               #    0.378 M/sec                           1,625,426 cycles                    #    2.486 GHz                             1,050,293 stalled-cycles-frontend   #   64.62% frontend cycles idle              838,781 stalled-cycles-backend    #   51.60% backend  cycles idle            1,055,735 instructions              #    0.65  insns per cycle                                                     #    0.99  stalled cycles per insn           210,587 branches                  #  322.106 M/sec                              10,809 branch-misses             #    5.13% of all branches               0.000945883 seconds time elapsed

 

輸出包含ls的已耗用時間,以及10個效能事件的統計。

task-clock:任務真正佔用的處理器時間。單位為ms。

CPUs utilized = task-clock / time elapsed,CPU的佔用率。

context-switches:內容相關的切換次數。

CPU-migrations:處理器遷移次數。

Linux為了維持多個處理器的負載平衡,在特定條件下會將某個任務從一個CPU

遷移到還有一個CPU。

page-faults:缺頁異常的次數。當應用程式請求的頁面尚未建立、請求的頁面不在記憶體中,或者請求的頁面儘管在內

存中,但物理地址和虛擬位址的映射關係尚未建立時。都會觸發一次缺頁異常。

另外TLB不命中。頁面訪問許可權不匹配

等情況也會觸發缺頁異常。

cycles:消耗的處理器周期數。假設把被ls使用的cpu cycles看成是一個處理器的。那麼它的主頻為2.486GHz。

能夠用cycles / task-clock算出。

stalled-cycles-frontend:略過。

stalled-cycles-backend:略過。

instructions:運行了多少條指令。IPC為平均每一個cpu cycle運行了多少條指令。

branches:遇到的分支指令數。branch-misses是預測錯誤的分支指令數。

 

(2) 經常使用參數

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

-a:system-wide collection from all CPUs. 從全部CPU上收集效能資料。

-r:repeat command and print average + stddev (max: 100). 反覆運行命令求平均。

-C:Count only on the list of CPUs provided (comma separated list), 從指定CPU上收集效能資料。

-v:be more verbose (show counter open errors, etc), 顯示很多其它效能資料。

-n:null run - don‘t start any counters,僅僅顯示任務的已耗用時間 。

-x SEP:指定輸出資料行的分隔字元。

-o file:指定輸出檔案,--append指定追加模式。

--pre <cmd>:運行目標程式前先啟動並執行程式。

--post <cmd>:運行目標程式後再啟動並執行程式。

 

(3) 使用範例

運行10次程式,給出標準差與期望的比值:

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

顯示更具體的資訊:

# perf stat -v ls > /dev/null

僅僅顯示任務已耗用時間,不顯示效能計數器:

# perf stat -n ls > /dev/null

單獨給出每一個CPU上的資訊:

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

ls命令運行了多少次系統調用:

# perf stat -e syscalls:sys_enter ls 

 

perf-record

 

收集採樣資訊,並將其記錄在資料檔案裡。

隨後能夠通過其他工具(perf-report)對資料檔案進行分析,結果類似於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) 經常使用參數

-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進程的效能資料:

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

記錄運行ls時的效能資料:

# perf record ls -g

記錄運行ls時的系統調用,能夠知道哪些系統調用最頻繁:

# perf record -e syscalls:sys_enter ls

 

perf-report

 

讀取perf record建立的資料檔案,並給出熱點分析結果。

 

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

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

 

(1) 經常使用參數

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

 

(2) 使用範例

# perf report -i perf.data.2

 

More

 

除了以上5個經常使用工具外,另一些適用於較特殊情境的工具。 比方核心鎖、slab分配器、調度器,

也支援自己定義探測點。

 

perf-lock

 

核心鎖的效能分析。

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) 輸出格式

                Name   acquired  contended total wait (ns)   max wait (ns)   min wait (ns)  &mm->page_table_...        382          0               0               0               0  &mm->page_table_...         72          0               0               0               0            &fs->lock         64          0               0               0               0          dcache_lock         62          0               0               0               0        vfsmount_lock         43          0               0               0               0  &newf->file_lock...         41          0               0               0               0 

 

Name:核心鎖的名字。

aquired:該鎖被直接獲得的次數,由於沒有其他核心路徑佔用該鎖。此時不用等待。

contended:該鎖等待後獲得的次數,此時被其他核心路徑佔用,須要等待。

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

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

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

最後另一個Summary:

=== output for debug===bad: 10, total: 246bad rate: 4.065041 %histogram of events caused bad sequence    acquire: 0   acquired: 0  contended: 0    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,顯示核心中調用kmalloc和kfree的地方。

--alloc:show per-allocation statistics。顯示分配的記憶體位址。

-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) 輸出格式

------------------------------------------------------------------------------------------------------ Callsite                           | Total_alloc/Per | Total_req/Per   | Hit      | Ping-pong | Frag------------------------------------------------------------------------------------------------------ perf_event_mmap+ec                 |    311296/8192  |    155952/4104  |       38 |        0 | 49.902% proc_reg_open+41                   |        64/64    |        40/40    |        1 |        0 | 37.500% __kmalloc_node+4d                  |      1024/1024  |       664/664   |        1 |        0 | 35.156% ext3_readdir+5bd                   |        64/64    |        48/48    |        1 |        0 | 25.000% load_elf_binary+8ec                |       512/512   |       392/392   |        1 |        0 | 23.438%


Callsite:核心代碼中調用kmalloc和kfree的地方。

Total_alloc/Per:總共分配的記憶體大小,平均每次分配的記憶體大小。

Total_req/Per:總共請求的記憶體大小,平均每次請求的記憶體大小。

Hit:調用的次數。

Ping-pong:kmalloc和kfree不被同一個CPU運行時的次數,這會導致cache效率減少。

Frag:片段所佔的百分比。片段 = 分配的記憶體 - 請求的記憶體,這部分是浪費的。

有使用--alloc選項,還會看到Alloc Ptr。即所分配記憶體的地址。

最後另一個Summary:

SUMMARY=======Total bytes requested: 290544Total bytes allocated: 447016Total bytes wasted on internal fragmentation: 156472Internal fragmentation: 35.003669%Cross CPU allocations: 2/509

 

probe-sched

 

調度模組分析。

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) 輸出格式

 ---------------------------------------------------------------------------------------------------------------  Task                  |   Runtime ms  | Switches | Average delay ms | Maximum delay ms | Maximum delay at     | ---------------------------------------------------------------------------------------------------------------  events/10:61          |      0.655 ms |       10 | avg:    0.045 ms | max:    0.161 ms | max at: 9804.958730 s  sleep:11156           |      2.263 ms |        4 | avg:    0.052 ms | max:    0.118 ms | max at: 9804.865552 s  edac-poller:1125      |      0.598 ms |       10 | avg:    0.042 ms | max:    0.113 ms | max at: 9804.958698 s  events/2:53           |      0.676 ms |       10 | avg:    0.037 ms | max:    0.102 ms | max at: 9814.751605 s  perf:11155            |      2.109 ms |        1 | avg:    0.068 ms | max:    0.068 ms | max at: 9814.867918 s


TASK:進程名和pid。

Runtime:實際的執行時間。

Switches:進程切換的次數。

Average delay:平均的調度延遲。

Maximum delay:最大的調度延遲。

Maximum delay at:最大調度延遲發生的時刻。

 

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函數的12處添加一個探測點。

 

Reference

 

[1]. Linux的系統級效能剖析工具系列,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

著作權聲明:本文博主原創文章。部落格,未經同意不得轉載。

系統級效能分析工具 — Perf

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.