Do I need volatile when timing a piece of code?

c++, timing, volatile

Solution

Formally, or practically? Formally, the calls to `std::chrono::high_resolution_clock::now()` aren't observable behavior, so the compiler can rearange them any way it wants. Practically, compilers will treat them as observable behavior, so you won't have any problems on this score. On the other hand, you'd better do something to ensure that `section_of_code_to_be_timed` actually does something. (I often make it a virtual member of a class, which introduces enough indirection to fool most compilers. And in the function itself, I ensure that it produces a result which will be visible outside of the function.)

Note that either way, `volatile` is irrelevant. About all it ensures is that `t0` and `dt` are written in the correct order (and in practice, it often won't ensure that); it makes no guarantees about `section_of_code_to_be_timed` with respect to `t0` or `dt`.

Problem

I want to auto-tune my code and for that must measure the time required by some section of code, for example ``` auto t0 = std::chrono::high_resolution_clock::now(); section_of_code_to_be_timed(arguments); auto dt = std::chrono::duration_cast<std::chrono::nanoseconds> (std::chrono::high_resolution_clock::now()-t0).counts(); // ... using dt to tweak auto-tuning parameters ``` What I worry about is that the compiler may re-arrange the calls to `std::chrono::high_resolution_clock::now()` and `section_of_code_to_be_timed()`, whereby invalidating my timing measurement. Is this a valid worry? If so, can I prevent it with declaring `t0` `volatile` or otherwise (how)? (I noticed that I could use the RAII idiom, similar to `std::lock_guard`, which doesn't seem to use `volatile`...)

Original source