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
...)
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
.
Use volatile to control access to unusual memory locations (such as hardware registers), where every read and write must happen in the order specified by the program. A normal variable, atomic or otherwise, doesn't usually require such control.
The two concepts are unrelated to each other. In particular, do not confuse volatile with a keyword used in other languages to make variables atomic. In C++, volatile has nothing to do with thread interactions whatsoever.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With