mardi 4 août 2015

Compiler optimization for a temporary object used as a "const &" function argument in a loop?

I have a forever thread loop below calling std::this_thread::sleep_for to delay 10 ms. The duration is a temp object std::chrono::milliseconds(10). The delay call seems "normal" and "typical" following some sample code. However looking a bit closer, it is evident that in each cycle the temp duration object is created and destroyed once.

// Loop A.
for (;;)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(10));
    // Do something.
}

Now if the duration object is created outside the loop (as a constant one), it will be constructed only once for all the cycles. Please see code below.

// Loop B.
const auto t = std::chrono::milliseconds(10);
for (;;)
{
    std::this_thread::sleep_for(t);
    // Do something.
}

Question: Since the std::this_thread::sleep_for uses "const &" as its argument type, will any C++ compiler optimize the temp duration object inside the Loop A into something like the Loop B?

I tried a simple test program below. The result shows that VC++ 2013 does not optimize the "const &" temp object.

#include <iostream>
#include <thread>

using namespace std;

class A {
public:
    A() { cout << "Ctor.\n"; }
    void ReadOnly() const {}  // Read-only method.
};

static void Foo(const A & a)
{
    a.ReadOnly();
}

int main()
{
    cout << "Temp object:\n";
    for (int i = 0; i < 3; ++i)
    {
        Foo(A());
    }

    cout << "Optimized:\n";
    const auto ca = A();
    for (int i = 0; i < 3; ++i)
    {
        Foo(ca);
    }
}
/* VC2013 Output:
Temp object:
Ctor.
Ctor.
Ctor.
Optimized:
Ctor.
*/

Aucun commentaire:

Enregistrer un commentaire