I was running the code below, which essentially does very little. It just adds 2 and four 100 million times and outputs the runtime.
#include "time.h"
#include <iostream>
using namespace std;
void add (){
int tot = 2+4;
}
void main(){
int t = clock();
int count = 0;
while(count<100000000){
int tot = 2+4;
count++;
}
cout <<endl<< "runtime = " << fixed <<(double) (clock() - t) / CLOCKS_PER_SEC <<"s" << endl;
}
But I was interested to see the time difference when doing the exact same thing but calling a function. So I replaced the line “int tot = 2+4” with “add()”.
I was expecting the second runtime to be slightly longer but was a lot longer. First implementation = .3s and second implementation = 3s.
I understand calling the function requires using the stack to store the return address and store local data. But it must be doing a lot more then this?
Would be great if someone could explain to me what exactly causes the big difference in runtime or maybe I am doing something silly.
As mentioned already by Seth, inline functions would probably get optimized.
In the 1st case (with basic optimizations on) most likely instead of constantly adding those 2 numbers it will resolve 2 + 4 to 6 and simply just do a simple
In the 2nd case since it is a function call the system has to
or something along these lines. As the call stack needs to be created for that function (ommitted return value push and such for simplicity). Once this function returns the stack pointer needs to be moved back previous to that first push and then the RET will set the instruction pointer back. As you can see this is more expensive than doing a simple
which is likely to be the case if you were doing just a simple (non optimized add)
EDIT: Here’s some more information about in-lining the function. When you inline the function it simply takes whatever functionality the function itself would do and places the instructions directly where it is reference instead of doing a CALL instruction and setting up a function call directly. For instance instead of
You will end up with
In code terms:
would become
assuming you inline the add function.