I was playing around with profiling certain things in C++ and I came across this very weird thing that I don't have an explanation for. Basically, the first function call made in main always takes significantly longer than any subsequent calls. This makes me think that the first function call has some kind of overhead. I'm not sure what this overhead would come from, so if anyone has any insights on why this is happening, I'd appreciate it. Also, I'm using Clang++
The a simple code snippet that shows this point is
#include <iostream> #include <time.h> const int size = 1000000; using namespace std; void foo() { int arr[size]; for(int i = 0; i < size; i++){ arr[i] = 1; } } int main(){ for(int i = 0; i < 10; i++){ clock_t t = clock(); foo(); t = clock() - t; cout << "cycles: " << t << endl; } return 0; } and the output shows that the first call always takes about 2000 more cycles than the rest of them
cycles: 5185 cycles: 3049 cycles: 2981 cycles: 2830 cycles: 2851 cycles: 2767 cycles: 2694 cycles: 2570 cycles: 2517 cycles: 2490