How do you tell the compiler to unroll loops based on the number of iterations or some other attribute? Or, how do you turn on loop unrolling optimization in Visual Studio 2005?
EDIT: E.g.
//Code Snippet 1
vector<int> b;
for(int i=0;i<3;++i) b.push_back(i);
As opposed to
//Code Snippet 2
vector<int> b;
b.push_back(0);
b.push_back(1);
b.push_back(2);
push_back() is an example, I could replace this with anything which can take a long time.
But I read somewhere that I can use Code 1 and the compiler can unroll it to Code 2 if the loop satisfies some criteria. So my question is: how do you do that? There's already a discussion on SO as to which one is more efficient but any comments on that is appreciated anyway.
It's generally fairly simple: "You enable optimizations".
If you tell the compiler to optimize your code, then loop unrolling is one of the many optimizations it tries to apply.
Keep in mind though, that unrolling is not always going to produce faster code. It might cause cache misses (in both data and instruction cache). And with the advanced branch prediction found in modern CPU's, the costs of the branches that make up a loop is often negligible.
Sometimes, the compiler may determine that unrolling would produce slower code, and then it won't do it.