Reputation: 2859
I have written this code:
inline int a_plus_b_power2(int a, int b) {
return (a + b) * (a + b);
}
int main() {
for(int a = 0; a < 9999999999999; ++a)
for(int b = 0; b < 999999999999; ++b)
a_plus_b_power2(a, b);
return 0;
}
but why the binary of this program doesn't differ with this program:
inline int a_plus_b_power2(int a, int b) {
return (a + b) * (a + b);
}
int main() {
for(int a = 0; a < 9; ++a)
for(int b = 0; b < 9; ++b)
a_plus_b_power2(a, b);
return 0;
}
Upvotes: 0
Views: 466
Reputation: 57749
Inlined functions are only "pasted" once per invocation.
In both your examples, the inlined function is only invoked once, although it is called many times.
I believe you want something like this:
for (unsigned int a = 0; a < 9; ++a)
{
for (unsigned int b = 0; b < 9; b+= 3) // Incremented by 3 because of 3 calls in loop.
{
a_plus_b_power_2(a, b + 0);
a_plus_b_power_2(a, b + 1);
a_plus_b_power_2(a, b + 2);
}
}
The above example may cause the compiler to paste the code inside your inline function 3 times within the loop and increase the size of the binary.
Note: turn off optimizations because optimizations may cause the compiler to convert the inline function into a standalone function inside the loop.
Upvotes: 2
Reputation: 16263
You are confusing function inlining with loop unrolling:
Loop unrolling means transforming
for (int i = 0; i < 4; i++)
a(i);
into
a(0); a(1); a(2); a(3);
while function inlining means transforming
void a(int i) { cout << i; }
for (int i = 0; i < 4; i++)
a(i);
into
for (int i = 0; i < 4; i++)
cout << i;
Compilers do have options to enable loop unrolling (look at -funroll-loops
and related options for gcc), but unless you poke them really hard, most of them will be very reluctant to unroll 999999999999 iterations... (the resulting binary would be multiple terabytes).
Upvotes: 6