This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
strange g++ optimization results on simple code
- From: Kai-Uwe Bux <bux at kubux dot net>
- To: gcc-help at gcc dot gnu dot org
- Date: Mon, 31 May 2004 16:01:42 -0400
- Subject: strange g++ optimization results on simple code
- Reply-to: Kai-Uwe Bux <bux at math dot cornell dot edu>
I am observing that turning a statement into an inline function
without actually changing the algorithm can improve code when g++
is told to optimize. I am using g++ version 3.4.0 (April 20 release)
on a Pentium 4.
I tried the following two files. Here is the "optimized" version:
// as.cc
// =====
#include <iostream>
inline
static
bool comp ( const unsigned int & a,
const unsigned int & b ) {
return( a < b );
}
int main ( void ) {
unsigned int A = 1000000000;
for ( unsigned i = 0; i < A; ++i ) {
if ( comp( A-2, i ) ) {
std::cout << i << std::endl;
}
}
}
// end of file
and this is the plain version:
// bs.cc
// =====
#include <iostream>
int main ( void ) {
unsigned int A = 1000000000;
for ( unsigned i = 0; i < A; ++i ) {
if ( A-2 < i ) {
std::cout << i << std::endl;
}
}
}
// end of file
Unoptimized I get:
gcc> time as.cc.out
999999999
real 0m8.326s
user 0m7.790s
sys 0m0.050s
gcc> time bs.cc.out
999999999
real 0m2.823s
user 0m2.670s
sys 0m0.010s
with -O, I get:
gcc> time as.cc.out
999999999
real 0m1.458s
user 0m1.360s
sys 0m0.010s
gcc> time bs.cc.out
999999999
real 0m1.432s
user 0m1.330s
sys 0m0.000s
with -O2, I get:
gcc> time as.cc.out
999999999
real 0m0.711s
user 0m0.650s
sys 0m0.000s
gcc> time bs.cc.out
999999999
real 0m1.265s
user 0m1.250s
sys 0m0.000s
and with -O3, I get:
gcc> time as.cc.out
999999999
real 0m0.529s
user 0m0.500s
sys 0m0.010s
gcc> time bs.cc.out
999999999
real 0m1.329s
user 0m1.250s
sys 0m0.000s
I do not understand, why as.cc appears to optimize better than bs.cc.
Actually, I do not understand, why different code is generated at all.
If someone who understands the internal magic of g++'s code generation
has an explanation as to why this happens, I would be very interested
in learning about it. Pointers would be highly appreciated: I searched
for optimization in gcc's bugzilla database and I tried a Google
search on optimization in g++, but I couldn't spot results pertinent
to my observation.
Thanks for your consideration
and best regards, Yours
Kai-Uwe Bux