BOOST_FOREACH less efficient than handcoded loop for some testcases
Erik
sigra@home.se
Thu Oct 11 12:42:00 GMT 2007
I made some tests of BOOST_FOREACH (from boost-1.34) to see if it
generates as good code as a handcoded loop. The answer is that it does
under certain circumstances. I tested g++-4.2.0 and g++-4.1.2 and the
optimizations levels O3, O2 and Os. Here is the first testcase (where a
reference to the vector is passed as a parameter):
//////////////////////////////////////////////////////////////////////////////
void f(float);
#include <boost/foreach.hpp>
#include <vector>
void g(const std::vector<float> & v) {
BOOST_FOREACH(float i, v)
f(i);
}
//////////////////////////////////////////////////////////////////////////////
This is as efficient as a handcoded loop if and only if the g++ version is 4.2.0 and the optimization level is O3. There will be 21 assembly instructions.
Here is the other testcase:
//////////////////////////////////////////////////////////////////////////////
void f(float);
#include <boost/foreach.hpp>
#include <vector>
struct A {
void g() const;
char name[52];
std::vector<float> const v;
};
void A::g() const {
BOOST_FOREACH(float i, v)
f(i);
}
//////////////////////////////////////////////////////////////////////////////
Unfortunately this gives as much as 24 instructions, while then handcoded version still gives only 21 instructions.
I attach the script I used for testing. If you want to try it yourself, put the script in an empty directory and run from there; it will create some files. After running it, it may be interesting to compare the generated code, for example:
diff -dU2 iterate_vector-member-g++-4.2.0-O3.s BOOST_FOREACH-member-g++-4.2.0-O3.s|kompare -
Can gcc be fixed so that it optimizes BOOST_FOREACH to be as efficient as a handcoded loop? Should I report it to the bugtracker?
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: iteration-test
URL: <https://gcc.gnu.org/pipermail/gcc-help/attachments/20071011/073f9121/attachment.ksh>
More information about the Gcc-help
mailing list