I am trying to test how inline function would save time for C++ compiler. So I write a demo code to test the running time difference between function using inline (f1) and another function not using inline(f2). However, after test, I found that the inline case will cost much more than not inline case. And I tried to change the test order of f1 and f2 in main function(test f2 cost time firt), in which case, f2 will cost less . Therefore, seems that the result will alwayss be the one in the front clock will cost more, there is no connection with inline or not inline. Why inline function in this case cost more time? code as follows:
#include <stdio.h>
#include <time.h>
#include <iostream>
#include <sstream>
using namespace std;
inline const string& f1(const string &s1, const string &s2)
{
return s1.size() < s2.size() ? s1 : s2;
}
const string& f2(const string &s1, const string &s2)
{
return s1.size() < s2.size() ? s1 : s2;
}
int main ()
{
clock_t start_t,end_t;
char s[10]="1000";
static int N = 100000;
clock_t start2_t,end2_t;
char s2[10]="1000";
static int i =0;
start_t = clock();
for(i = 0;i<N;i++)
f1("100",s);
end_t = clock();
start2_t = clock();
for(i = 0 ;i<N;i++)
f2("100",s);
end2_t = clock();
printf("Inline:It took %d .\n",(int)(end_t - start_t));
printf("No-Inline:It took %d .\n",(int)(end2_t - start2_t));
}
Here comes result:
Inline:It took 10246 .
No-Inline:It took 9385 .