I have just finished inline functions chapter in Bruce Eckel's : thinking in C++. Well there's an exercise which asks you to create two exact functions one being inline and the other not. Then use clock() and count the time passed for each one. I have worked on similar problems and I don't think there's anything complex with it. Therefore I came up with :
#include <iostream> #include <ctime> using namespace std; inline int infun(int x) { x = 3; x = 5; cout << ""; return x; } int fun(int x) { x = 3; x = 5; cout << ""; return x; } int main() { clock_t startIn = clock(); for (int i = 0; i < 10000000; i++) { infun(i); } clock_t finishIn = clock(); clock_t start = clock(); for (int i = 0; i < 10000000; i++) { fun(i); } clock_t finish = clock(); clock_t startIn2 = clock(); for (int i = 0; i < 10000000; i++) { infun(i); } clock_t finishIn2 = clock(); cout << "Inline: " << (finishIn - startIn) << endl << "Regular Function: " << (finish - start) << endl<< "Second Inline: " << finishIn2 - startIn2 << endl; return 0; } Output
Inline: 195842 Regular Function: 166564 Second Inline: 162917 So I have 3 functions. 2 exactly similar inlines and one non-inline (for testing purposes I came up with this case).
a) Why the first inline takes all that time (the same happens for any function executed first) b) Why if the repetitions are decreased (lets say 1000) the normal function is faster than the others.
My test cases are satisfied even with simpler functions like :
inline int infun(int x) { return x; } I've also checked the assembly output to ensure that the inlines are truly inlines or that g++ does not promote the non-inline to inline. Thank you for your time, any feedback is appreciated.
inlineis simply a recommendation, the compiler makes its own determination on whether to actually inline the code. From there cache effects might give different timing on the exact same code. Also there's a lot of granularity in the standardclock, you might see a huge difference that isn't real.