0

On this sample code:

#include <iostream>
using namespace std;

int main()
{
    cout<<"Hello World!"<<endl;

    return 0;
}

I ran the following command 3 times:

perf stat -e cpu-cycles ./sample

Following are the 3 outputs on consecutive executions:

1)

Hello World!

Performance counter stats for './try':

     22,71,970      cpu-cycles               

   0.003634105 seconds time elapsed

2)

Hello World!

 Performance counter stats for './try':

     18,51,044      cpu-cycles               

   0.001045616 seconds time elapsed

3)

Hello World!

 Performance counter stats for './try':

     18,21,834      cpu-cycles               

   0.001153489 seconds time elapsed

Why would the same program take different number of cpu-cycles on multiple runs?

I am using "Intel(R) Core(TM) i5-5250U CPU @ 1.60GHz", "Ubuntu 14.04.3 LTS" and "g++ 4.8.4".

vervenumen
  • 657
  • 7
  • 13
  • I think that this question must be reopened. The linked question mostly focuses on the peculiarities of `sleep`. I believe that in this case the variation has a different explanation. – Leon Jul 31 '16 at 20:38
  • For one, your program mostly does I/O. i.e. interacting with the outside (ever-changing and unpredictable) world. – n. m. could be an AI Aug 01 '16 at 05:47

1 Answers1

1

During start-up of the program the binary code is memory-mapped but loaded lazily (as needed). Hence, during the first invocation of the program some CPU cycles are spent by the kernel on (transparently) loading the binary code as execution hits instruction pages that are not yet in the RAM. Subsequent invocations take less time since they reuse the cached code, unless the underlying file has changed or the program hasn't been executed for a long time and its pages were recycled.

Leon
  • 31,443
  • 4
  • 72
  • 97