簡體   English   中英

基准測試中不同“for”的不同行為

[英]different behavior for different "for"s in benchmark

我們可以使用google benchmarkhttps://www.quick-bench.com/編寫一個簡單的基准測試,

static void range_based_for(benchmark::State &state) {
    for (auto _ : state) {
        std::to_string(__LINE__);
    }
}
BENCHMARK(range_based_for);

我們也可以用 std::for_each 重寫它,

static void std_for_each(benchmark::State &state) {
    std::for_each (std::begin(state), std::end(state), [] (auto _) {
        std::to_string(__LINE__);
    });
}
BENCHMARK(std_for_each);

一切都是好的。 但是,當我們使用 old school 進行聲明時,它會在沒有完成的情況下運行。

static void old_school_for(benchmark::State &state) {
    for (auto iter = std::begin(state); iter != std::end(state); ++iter) {
        std::to_string(__LINE__);
    };
}
BENCHMARK(old_school_for);

其實std::for_each就是用這種風格實現的。 他們的行為如何不同?

begin / end函數記錄有警告:說“不應直接調用這些函數”

不應直接調用這些函數。

要求:基准測試尚未開始運行。 begin 和 end 之前都沒有被調用過。

end調用StartKeepRunning

StartKeepRunning有什么作用? 它將迭代次數重置為最大值

很明顯,您只應該調用beginend一次。 第三個循環的不同之處在於每次迭代都會調用一次std::end(state) ,這顯然會將迭代計數重置為最大值。

我不知道為什么圖書館是這樣設計的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM