Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need volatile when timing a piece of code?

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...)

like image 378
Walter Avatar asked Dec 03 '13 12:12

Walter


2 Answers

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.

like image 64
James Kanze Avatar answered Oct 14 '22 03:10

James Kanze


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.

like image 23
Vizllx Avatar answered Oct 14 '22 02:10

Vizllx