Preventing compiler optimizations while benchmarking

前端 未结 2 1093
北海茫月
北海茫月 2020-12-03 01:50

I recently came across this brilliant cpp2015 talk CppCon 2015: Chandler Carruth \"Tuning C++: Benchmarks, and CPUs, and Compilers! Oh My!\"

One of the techniques me

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 02:27

    1) What is the advantage of an escape over clobber ?

    escape() doesn't have an advantage over clobber(). escape() complements clobber() in the following important way:

    The effect of clobber() is limited to memory that is potentially accessible through an imaginary global root pointer. In other words, compiler's model of the allocated memory is a connected graph of blocks referring to each other through pointers, and the said imaginary global root pointer serves as an entry point to that graph. (Memory leaks are not accounted for in this model, i.e. the compiler ignores the possibility that once accessible blocks may become inaccessible because of a lost pointer value). A newly allocated block is not a part of a such graph, and is immune to any side-effects of clobber(). escape() ensures that the passed in address belongs to the globally accessible set of memory blocks. When applied to a newly allocated memory block, escape() has the effect of adding it to the said graph.

    2) From the example above it looks like clobber() prevents the previous statement ( push_back ) to be optimized way. If that's the case why the below snippet is not correct ?

     void benchmark()
     {
         vector v;
         v.reserve(1);
         v.push_back(10);
         clobber();
     }
    

    The allocation hidden inside v.reserve(1) is not visible to clobber() until it is registered via escape().

提交回复
热议问题