天天看點

d避免優化代碼塊

​​原文​​​ 如何防止​

​編譯器​

​删除想要​

​測量​

​代碼?

為了防止​

​優化器​

​​完全​

​忽略​

​​函數,需要處理​

​傳回值​

​​,一般,即要把​

​傳回值​

​​合并到某個​

​累加變量​

​​中,如,如果它是​

​int​

​​函數,就有個你​

​要加的​

​​運作的​

​int​

​累加器:

int funcToBeMeasured(...) pure { ... }
    int accum;
    auto results = benchmark!({
         //這裡不要隻調用`funcToBeMeasured`而忽略該值,否則優化器可能會完全删除調用
        accum += funcToBeMeasured(...);
    });      

然後在結束​

​基準測試​

​​時,處理​

​累積的值​

​​,比如列印到​

​stdout​

​​中,這樣​

​優化器​

​就以為用了它,就不會删它.

void main()
{
    import std.datetime.stopwatch;
    import std.stdio: write, writeln, writef, writefln;
    import std.conv : to;

    void f0() {}
    void f1()
    {
        foreach(i; 0..4_000_000)
        {
            // 會優化循環
        }
    }
    void f2()
    {
        foreach(i; 0..4_000_000)
        {
            // 避免優化
            asm @safe pure nothrow @nogc {}
        }
    }
    auto r = benchmark!(f0, f1, f2)(1);
    writeln(r[0]); // 4微秒
    writeln(r[1]); // 4微秒
    writeln(r[2]); // 1毫秒
}      

繼續閱讀