在工作中排查問題的時候,我們經常需要通過獲取某個函數的執行時間來定位問題。比較原始的方式是通過在代碼中埋點,然後打印出不通點上的時間戳,或者計算點之間的時間差,這種方式簡單直接。但是在沒有源代碼的時候,或者如果要在某個在線的系統上獲取相關信息的時候,這種方式就無能爲力了。但是通過perf ,我們很容易辦到。
下面我們以獲取內核中函數 pci_reset_function的執行時間爲例來介紹具體怎麼做:
root@ll:~$ perf probe pci_reset_function
Added new event:
probe:pci_reset_function (on pci_reset_function)
You can now use it in all perf tools, such as:
perf record -e probe:pci_reset_function -aR sleep 1
root@ll:~$ perf probe -f 'pci_reset_function%return'
Added new event:
probe:pci_reset_function_1 (on pci_reset_function%return)
You can now use it in all perf tools, such as:
perf record -e probe:pci_reset_function_1 -aR sleep 1
root@ll:~$ perf record -e probe:pci_reset_function -e probe:pci_reset_function_1 -aR -T sleep 15
[ perf record: Woken up 1 times to write data ]
[ perf record: Captured and wrote 0.863 MB perf.data ]
root@ll$ perf script
qemu-system-x86 17243 [001] 679865.714931: probe:pci_reset_function: (ffffffff8135b930)
qemu-system-x86 17243 [001] 679866.719016: probe:pci_reset_function_1: (ffffffff8135b930 <- ffffffffa08057d0)
通過perf script 即可獲函數進入以及返回的時間戳,那麼獲取函數的執行時間就很簡單了。對於用戶態的應用程序,採用的方式類似。