title: Why do these instruction counts of ls differ so much? (ptrace vs perf vs qemu)
body: <p>I want to count the total number of instructions executed when running /bin/ls.
  I used 3 methods whose results differ heavily and i dont have a clue why.</p>
  <p><strong>1. Instruction counting with ptrace</strong></p>
  <p>I wrote a piece of code that invokes an instance of ls and singlesteps through it with ptrace:</p>
  <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt;
  #include &lt;sys/ptrace.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/wait.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;sys/user.h&gt;
  #include &lt;sys/reg.h&gt;    
  #include &lt;sys/syscall.h&gt;
  
  int main()
  {   
      pid_t child;
      child = fork(); //create child
      
      if(child == 0) {
          ptrace(PTRACE_TRACEME, 0, NULL, NULL);
          char* child_argv[] = {&quot;/bin/ls&quot;, NULL};
          execv(&quot;/bin/ls&quot;, child_argv);
      }
      else {
          int status;
          long long ins_count = 0;
          while(1)
          {
              //stop tracing if child terminated successfully
              wait(&amp;status);
              if(WIFEXITED(status))
                  break;
  
                  ins_count++;
                  ptrace(PTRACE_SINGLESTEP, child, NULL, NULL);
          }
  
      printf(&quot;\n%lld Instructions executed.\n&quot;, ins_count);
  
      }
      
      return 0;
  }
  </code></pre>
  <p>Running this code gives me 516.678 Instructions executed.</p>
  <p><strong>2. QEMU singlestepping</strong></p>
  <p>I simulated ls using qemu in singlestep mode and logged all incoming instructions into a log file using the following command:
  <em>qemu-x86_64 -singlestep -D logfile -d in_asm /bin/ls</em></p>
  <p>According to qemu ls executes 16.836 instructions.</p>
  <p><strong>3. perf</strong></p>
  <p><em>sudo perf stat ls</em></p>
  <p>This command gave me 8.162.180 instructions executed.</p>
  <p>I know that most of these instructions come from the dynamic linker and it is fine that they get counted. But why do these numbers differ so much? Shouldn't they all be the same?</p>