1

I want to profile a certain function and in order to get more reliable results I call the function in a loop. I was concerned that the compiler would see that I never use the result and optimize away my loop, so I thought I could just copy the result to a variable marked as volatile to prevent that (demo here).

#include <chrono>

struct Bar{};
Bar foo();

Bar profile_foo()
{
    // result is marked volatile so the loop isn't optimized away
    volatile Bar result;

    for(int i = 0; i< 10000; i++)
        result = foo();

    return result;
}

int main(int argc, char* argv[])
{
    using namespace std::chrono;
    auto begin = high_resolution_clock::now();

    auto result = profile_foo();

    auto end = high_resolution_clock::now();
    auto time_passed = duration_cast<milliseconds>(end-begin).count();

    // validate result ...
}

Turns out there is no default copy constructor/assignment operator between a volatile/non-volatile instance of a class. See this post.

So,

  1. is there any other way to assign a non-volatile to a volatile and vice versa? Or,
  2. is there another way to tell the compiler not to optimize away the loop?

Note: I cannot modify the class Bar.

Community
  • 1
  • 1
bgp2000
  • 1,200
  • 12
  • 30
  • Does Bar have a data member that is POD? So you could do something like `volatile double temp;` `temp = foo().getSomeDouble()` ? – RyanP Jan 11 '17 at 15:48
  • If the function `foo` has explicit side effects or if it is defined in another compilation unit (the compiler cannot know whether side effects are present), the loop should not be optimized out. – Serge Ballesta Jan 11 '17 at 16:13
  • @serge-ballesta foo might not have side effects and resides in a static lib. I think that aggresive link time optimization might still decide to optimize away. – bgp2000 Jan 11 '17 at 16:49
  • @ryanp That might work. That could then be generalized to `volatile Bar* tmp; tmp = &result;`. – bgp2000 Jan 11 '17 at 16:52

0 Answers0