2

My understanding is that C++ reorders code when optimizing and simple timers might not provide accurate results for timing execution time. Can someone provide an example where the following code could be reordered?

auto t0 = clock();
auto r = someLongRunningFunc();
auto t1 = clock();
std::cout << r << "  time: " << t1 - t0 << std::endl;

to where someLongRunningFunc() is invoked before the first call to clock() or after the second call to clock()?

FWIW - I'm using Visual Studio 17, and I can't seem to write a function which accomplishes this.

lots_of_questions
  • 1,109
  • 3
  • 16
  • 24

1 Answers1

0

Compiler optimizations should not change the meaning of your code.

In Caribou's example, he introduced an important issue: that "long running function" was the same as an integer assignment. You aren't going to be able to clock() that, and the compiler (rightly) optimized it as inconsequential.

Do something that is more complex than returning a constant value, that actually is long running or has side effects (such as I/O) and the compiler cannot safely rearrange your clock()s.

There do exist “unsafe” optimizations. Compilers (good ones, at least) never apply these unless you specifically ask for them. This works under the usual C & C++ caveat: the programmer knows what he is doing when he tells the compiler to “do what I say”.

Dúthomhas
  • 8,200
  • 2
  • 17
  • 39