jeudi 20 octobre 2016

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)
        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)
{
    if (done) {
        b.setFillColor(color);
        done = false;
    }
}

Execution time: <12ms

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);
    }
}

Basing on the benchmarked code, to optimize this, should I turn it into:

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.

Aucun commentaire:

Enregistrer un commentaire