Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent code being moved by GCC in benchmark code

Tags:

c++

gcc

I'm trying to fine tune some benchmark code we are using and am wondering if there is a way to communicate to GCC explicitly how to order certain bits of code. For example, given these blocks of code:

  1. Pre
  2. Start-Timer
  3. Body
  4. Stop-Timer
  5. Post

I wish to tell GCC that each block must be kept in the above order without any instruction leakage into the other block. Ideally the timer would measure only Step 3, however, for practical reasons measuring at least Step 3 and at most Steps 2-4 will suffice. I just want to make sure I'm note measuring any part of Step 1 or 5.

Currently I use a __sync_synchronize in the Timer functions to issue a full memory fence. My hope is that, in addition to being a fence, that this function is marked to prevent reordering.

Is this call to __sync_synchronize sufficient? Also logically, would the C++11 fence commands also suffice according to the text of the standard?

like image 651
edA-qa mort-ora-y Avatar asked Nov 04 '22 06:11

edA-qa mort-ora-y


1 Answers

If the Start-Timer is a function call and the Stop-Timer is another function call, the optimizer has little opportunity to move the Body around, or spill material from Pre or Post into Body.

All the side-effects from Pre must be complete before the Start-Timer function is called (there's a sequence point there). All the side effects of Stop-Timer must be complete before executing Post (there's a sequence point there, too). So the compiler would have to have the code for Start-Timer and Stop-Timer visible to monkey with the generated code, spilling material around, and I'm not convinced it could do so even then.

So, in summary, I don't think you have to worry about it if you use function calls to start and stop the timer.

like image 165
Jonathan Leffler Avatar answered Nov 12 '22 17:11

Jonathan Leffler