“Escape” and “Clobber” equivalent in MSVC

前端 未结 2 1908
悲&欢浪女
悲&欢浪女 2020-12-29 06:24

In Chandler Carruth\'s CppCon 2015 talk he introduces two magical functions for defeating the optimizer without any extra performance penalties.

For reference, here

2条回答
  •  庸人自扰
    2020-12-29 07:01

    While I don't know of an equivalent assembly trick for MSVC, Facebook uses the following in their Folly benchmark library:

    /**
     * Call doNotOptimizeAway(var) against variables that you use for
     * benchmarking but otherwise are useless. The compiler tends to do a
     * good job at eliminating unused variables, and this function fools
     * it into thinking var is in fact needed.
     */
    #ifdef _MSC_VER
    
    #pragma optimize("", off)
    
    template 
    void doNotOptimizeAway(T&& datum) {
      datum = datum;
    }
    
    #pragma optimize("", on)
    
    #elif defined(__clang__)
    
    template 
    __attribute__((__optnone__)) void doNotOptimizeAway(T&& /* datum */) {}
    
    #else
    
    template 
    void doNotOptimizeAway(T&& datum) {
      asm volatile("" : "+r" (datum));
    }
    
    #endif
    

    Here is a link to code on GitHub.

提交回复
热议问题