为什么perf显示sleep占用所有内核?

Why does perf show that sleep takes all cores?

我正在尝试根据我编写的各种程序来熟悉 perf 和 运行 它。

当我针对 100% 单线程的程序启动它时,perf 显示它在机器上占用两个内核(任务时钟事件)。 这是示例输出:

perf stat  -a --per-core python3 test.py

Performance counter stats for 'system wide':

    S0-C0           1       19004.951263      task-clock (msec) # 1.000 CPUs utilized            (100.00%)
    S0-C0           1              5,582      context-switches                                              (100.00%)
    S0-C0           1                 19      cpu-migrations                                                (100.00%)
    S0-C0           1              3,746      page-faults                                                 
    S0-C0           1    <not supported>      cycles                   
    S0-C0           1    <not supported>      stalled-cycles-frontend  
    S0-C0           1    <not supported>      stalled-cycles-backend   
    S0-C0           1    <not supported>      instructions             
    S0-C0           1    <not supported>      branches                 
    S0-C0           1    <not supported>      branch-misses            
    S0-C1           1       19004.950059      task-clock (msec) # 1.000 CPUs utilized            (100.00%)
    S0-C1           1              6,752      context-switches                                              (100.00%)
    S0-C1           1                 25      cpu-migrations                                                (100.00%)
    S0-C1           1                935      page-faults                                                 
    S0-C1           1    <not supported>      cycles                   
    S0-C1           1    <not supported>      stalled-cycles-frontend  
    S0-C1           1    <not supported>      stalled-cycles-backend   
    S0-C1           1    <not supported>      instructions             
    S0-C1           1    <not supported>      branches                 
    S0-C1           1    <not supported>      branch-misses            

      19.004688019 seconds time elapsed

它甚至表明简单的 sleep 命令在我的计算机上占用了两个内核,我无法解释这一点。我知道 OS 调度程序可以为任何进程重新分配活动核心,但在这种情况下 CPU 利用率会反映这一点。

谁能解释一下?

谢谢!

根据 perf stat 子命令的手册页,您有 -a 选项来分析整个系统: http://man7.org/linux/man-pages/man1/perf-stat.1.html

   -a, --all-cpus
       system-wide collection from all CPUs (default if no target is
       specified)

在此"system-wide"模式下,perf stat(和perf record too)将计算系统中所有CPU的事件(或record的配置文件) .当在没有附加参数 command 的情况下使用时,perf 将 运行 直到被 Ctrl-C 中断。使用参数 command,perf 将 count/profile 直到命令生效。典型用法是

perf stat -a sleep 10      # Profile counting every CPU for 10 seconds
perf record -a sleep 10    # Profile with cycles every CPU for 10 seconds to perf.data

要获取单个命令的统计信息,请使用单个进程分析(不带 -a 选项)

perf stat python3 test.py

对于分析 (perf record),您可以 运行 不使用 -a 选项;或者你可以使用 -a 然后在 perf report 中做一些手动过滤,只关注你的应用程序的 pids/tids/dsos (如果命令配置文件使用一些进程间请求到其他守护进程来做很多 CPU 工作)。

--per-core, -A, -C <cpulist>, --per-socket 选项仅适用于系统范围的 -a 模式。尝试 --per-thread-p pid 附加到进程选项。