perf 性能分析工具

1. perf简介

perf是一款Linux性能分析工具。Linux性能计数器是一个新的基于内核的子系统,它提供一个性能分析框架,比如硬件(CPU、PMU(Performance Monitoring Unit))功能和软件(软件计数器、tracepoint)功能。
通过perf,应用程序可以利用PMU、tracepoint和内核中的计数器来进行性能统计。它不但可以分析制定应用程序的性能问题(per thread),也可以用来分析内核的性能问题,当然也可以同事分析应用程序和内核,从而全面理解应用程序中的性能瓶颈。

2. perf 安装

2.1 源码安装

终端进入/usr/src目录,获取源代码

sudo apt-get install linux-source-x.x.x

进入linux-source.x.x.x,解压linux-source.x.x.x.tar.bz2

sudo tar -jxvf linux-source-x.x.x.tar.bz2

进入linux-source-x.x.x/tools/perf/

make
make install

2.2 package 安装

sudo apt install linux-tools-common

输入perf ,按提示安装缺少的组件

3. perf的使用

3.1 perf --help 查看提示

3.2 perf stat

概括精简的方式提供被调试程序的整体情况和汇总数据

测试程序 t1:

//test.c 
void longa() 
{ 
  int i,j; 
  for(i = 0; i < 1000000; i++) 
  j=i; //am I silly or crazy? I feel boring and desperate. 
} 
 
void foo2() 
{ 
  int i; 
  for(i=0 ; i < 10; i++) 
       longa(); 
} 
 
void foo1() 
{ 
  int i; 
  for(i = 0; i< 100; i++) 
     longa(); 
} 
 
int main(void) 
{ 
  foo1(); 
  foo2(); 
}

编译:

gcc – o t1 – g test.c

调优:perf stat ./t1 (需要root 权限)

x@x-VirtualBox:~/test$ sudo perf stat ./t1
[sudo] password for x:

 Performance counter stats for './t1':

            342.75 msec task-clock                #    0.990 CPUs utilized
                 2      context-switches          #    0.006 K/sec
                 0      cpu-migrations            #    0.000 K/sec
                45      page-faults               #    0.131 K/sec
   <not supported>      cycles
   <not supported>      instructions
   <not supported>      branches
   <not supported>      branch-misses

       0.346364798 seconds time elapsed

       0.332232000 seconds user
       0.014137000 seconds sys

统计信息:

  • task-clock :最高占用率的任务(cpu,io)
  • context-switches: 进程切换次数
  • 。。。

3.2 perf top

Perf top 用于实时显示当前系统的性能统计信息。该命令主要用来观察整个系统当前的状态,比如可以通过查看该命令的输出来查看当前系统最耗时的内核函数或某个用户进程。

3.3 perf record

需要一些粒度更细的信息.

随后可以通过其它工具(perf-report)对数据文件进行分析,结果类似于perf-top的

3.4 perf report

读取perf record创建的数据文件,并给出热点分析结果

参考: 1. Perf -- Linux下的系统性能调优工具,第 1 部分

    2. Perf -- Linux下的系统性能调优工具,第 2 部分

    3. 系统级性能分析工具 — Perf

原文地址:https://www.cnblogs.com/x-police/p/12369933.html