How to count number of executed instructions of a process id including all future child threads

前端 未结 1 1508
自闭症患者
自闭症患者 2021-01-03 05:18

Some times ago, I asked the following question "How to count number of executed instructions of a process id including child processes", and @M-Iduoad kindly provi

相关标签:
1条回答
  • 2021-01-03 05:32

    The combination of perf record -s and perf report -T should give you the information you need.

    To demonstrate, take the following example code using threads with well-defined instruction counts:

    #include <cstdint>
    #include <thread>
    
    void work(int64_t count) {
        for (int64_t i = 0; i < count; i++);
    }
    
    int main() {
        std::thread first(work, 100000000ll);
        std::thread second(work, 400000000ll);
        std::thread third(work, 800000000ll);
        first.join();
        second.join();
        third.join();
    }
    

    (Compile without optimization!)

    Now, use perf record as a prefix command. It will follow all spawned processes and threads.

    $ perf record -s -e instructions -c 1000000000 ./a.out
    [ perf record: Woken up 1 times to write data ]
    [ perf record: Captured and wrote 0.003 MB perf.data (5 samples) ]
    

    To display the statistics nicely:

    $ perf report -T
    [... snip ...]
    #    PID     TID  instructions:u
      270682  270683       500003888
      270682  270684      2000001866
      270682  270685      4000002177
    

    The parameters for perf record are a little bit tricky. -s writes separate records with fairly precise numbers - they do not depend on the instruction samples (generated every 1000000000 instructions). However, perf report, even with -T fails when it does not find a single sample. So you need to set a instruction sample count -c (or frequency) that triggers at least once. Any sample will do, it does not need a sample per thread.

    Alternatively, you could look at the raw records from perf.data. Then you can actually tell perf record to not collect any samples.

    $ perf record -s -e instructions -n ./a.out             
    [ perf record: Woken up 1 times to write data ]
    [ perf record: Captured and wrote 0.003 MB perf.data ]
    

    But you need to filter out the relevant records and there might be additional records you need to sum up.

    $ perf script -D | grep PERF_RECORD_READ | grep -v " 0$"
    # Annotation by me                              PID    TID 
    213962455637481 0x760 [0x40]: PERF_RECORD_READ: 270887 270888 instructions:u 500003881
    213963194850657 0x890 [0x40]: PERF_RECORD_READ: 270887 270889 instructions:u 2000001874
    213964190418415 0x9c0 [0x40]: PERF_RECORD_READ: 270887 270890 instructions:u 4000002175
    
    0 讨论(0)
提交回复
热议问题