whats the smartest way to do something only once per iteration in a nested loop? i can't pull out the invariant part because the outer loop is very complex. Here is my C++ example:

void foo::bar() {
    if(oldCycle == tree.cycle) {
        doSomething();
        oldCycle++;
    }
}

this method is called very often until tree.cycle is incremented. oldCycle is a private member variable of foo

claas foo {
public: ...

private:
int oldCycle;
};

Does the compiler optimize this code or will the if check run every iteration?

Edit: Here like requested the code with the loops: the first loop is in the mexFunction() method, the algorithm is started in matlab and calls the mexFunction.

void mexFunction(...) {
    for( tree.cycle = 0; tree.cycle<maxIt; tree.cycle++ ) {
        foo->startfoo();
    }
}

and here is the other loop:

void foo::startfoo() {
    for(tree.cur_it = 0; tree.cur_it <=39; tree.cur_it++ ) {
        bar();
    }
}
有帮助吗?

解决方案

For a general condition, you can't really optimize this out, since you would need to remove the special case from the collection one way or another.

However, for the special case of treating the first element specially (e.g. when printing a range with de­li­mit­ers as "1, 2, 3"), you can use Knuth's "loop-and-a-half":

Naive loop:

for (unsigned int i = 0; i != values.size(); ++i)
{
    if (i != 0) { std::cout << ", "; }
    std::cout << values[i];
}

Loop-and-a-half:

if (!values.empty())
{
    for (unsigned int i = 0; ; )
    {
        std::cout << values[i];
        ++i;
        if (i == values.size()) { break; }
        std::cout << ", ";
    }
}

The latter construction is more involved, but saves you the mostly false check i != 0.

That said, it's quite plausible that a good compiler will do the partial unrolling even if you write the code the naive way.

其他提示

For simple cases I prefer this method.

if ( ! values.empty())
{
    std::cout << values[0];

    for (size_t z = 1; z < values.size(); z++)
    {
        std::cout << ", " << values[z];
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top