18.2. 使用 perf stat 计数事件
您可以使用 perf stat
计算命令执行过程中出现的硬件和软件事件,并生成这些计数的统计信息。默认情况下,perf stat
以针对每个线程的模式运行。
先决条件
-
已安装
perf
用户空间工具,如安装 perf 所述。
流程
计算事件数。
在没有 root 访问权限的情况下运行
perf stat
命令只会计算在用户空间中出现的事件:$ perf stat ls
例 18.1. perf stat 的输出在没有 root 访问权限的情况下运行
Desktop Documents Downloads Music Pictures Public Templates Videos Performance counter stats for 'ls': 1.28 msec task-clock:u # 0.165 CPUs utilized 0 context-switches:u # 0.000 M/sec 0 cpu-migrations:u # 0.000 K/sec 104 page-faults:u # 0.081 M/sec 1,054,302 cycles:u # 0.823 GHz 1,136,989 instructions:u # 1.08 insn per cycle 228,531 branches:u # 178.447 M/sec 11,331 branch-misses:u # 4.96% of all branches 0.007754312 seconds time elapsed 0.000000000 seconds user 0.007717000 seconds sys
如上例中所示,如果
perf stat
运行没有 root 访问权限,则事件名称会加上:u
,表示这些事件只在用户空间中计算出来。要计算用户空间和内核空间事件,在运行
perf stat
时必须具有 root 访问权限:# perf stat ls
例 18.2. 使用 root 访问权限运行 perf stat 的输出
Desktop Documents Downloads Music Pictures Public Templates Videos Performance counter stats for 'ls': 3.09 msec task-clock # 0.119 CPUs utilized 18 context-switches # 0.006 M/sec 3 cpu-migrations # 0.969 K/sec 108 page-faults # 0.035 M/sec 6,576,004 cycles # 2.125 GHz 5,694,223 instructions # 0.87 insn per cycle 1,092,372 branches # 352.960 M/sec 31,515 branch-misses # 2.89% of all branches 0.026020043 seconds time elapsed 0.000000000 seconds user 0.014061000 seconds sys
默认情况下,
perf stat
以针对每个线程的模式运行。要更改为 CPU 范围事件计数,请将-a
选项传递给perf stat
。要计算 CPU 范围内的事件,您需要 root 访问权限:# perf stat -a ls
其他资源
-
您系统上的
perf-stat (1)
手册页