LightTab2 LightTab2 - 1 month ago 9
C++ Question

Loop optimalization: should I use booleans to minimize CPU usage?

I've done some benchmarks of following codes, with full optimalization (/Ox) :

sf::Text b;
sf::Color color = sf::Color(255, 255, 255, 255);
for (int x = 0; x < 9999999; ++x) //imagine it's the gameloop
b.setFillColor(color);


Execution time: >80ms

sf::Text b;
sf::Color color = sf::Color(255, 255, 255, 255);
bool done = true;
for (int x = 0; x < 9999999; ++x) //imagine it's the gameloop
{
if (done) {
b.setFillColor(color);
done = false;
}
}


Execution time: <12ms
I want to obtain the result of b.setFillColor(color), only once, so I'm using boolean. Should I use in the situation described below?:

sf::Vector2f mousepos;
//Get the cursor position
sf::Text b[2];
sf::FloatRect b_rec[2] = {b[0].getGlobalBounds(), b[1].getGlobalBounds()};
sf::Color on = sf::Color(255,255,255), off = sf::Color(127, 255, 255);
for (;;) //this is the gameloop
{
if (b_rec[0].contains(mousepos))
{
b[0].setFillColor(on); b[1].setFillColor(on);
}
else if (b_rec[1].contains(mousepos))
{
b[0].setFillColor(off); b[1].setFillColor(on);
}
else {
b[0].setFillColor(off); b[1].setFillColor(off);
}
}


With boolean:

sf::Vector2f mousepos;
//Get the cursor position
sf::Text b[2];
sf::FloatRect b_rec[2] = {b[0].getGlobalBounds(), b[1].getGlobalBounds()};
sf::Color on = sf::Color(255,255,255), off = sf::Color(127, 255, 255);

bool done = true;
for (;;) //this is the gameloop
{
if (b_rec[0].contains(mousepos))
{
b[0].setFillColor(on); b[1].setFillColor(on);
done = true;
}
else if (b_rec[1].contains(mousepos))
{
b[0].setFillColor(off); b[1].setFillColor(on);
done = true;
}
else if (done){
b[0].setFillColor(off); b[1].setFillColor(off);
done = false;
}
}


Clearly, it hurts transparency of the code, isn't there a "better" way?
I am sorry if there seems to be too much code in these examples, I tried to shorten it as I could.

Answer

I think you have a misunderstanding on what this code does:

sf::Text b;
sf::Color color = sf::Color(255, 255, 255, 255);
bool done = true;
for (int x = 0; x < 9999999; ++x) //imagine it's the gameloop
{
    if (done) {
        b.setFillColor(color);
        done = false;
    }
}

The condition of the if is true exactly once. After that you run a loop that does nothing. This explains your timing results. You compare a loop that does ~10^x times something with a loop that does nothing but only in its first iteration.

Comments