gpt4 book ai didi

c++ - atomic fetch_add 与添加性能

转载 作者:可可西里 更新时间:2023-11-01 18:39:01 27 4
gpt4 key购买 nike

下面的代码展示了多线程编程的奇妙之处。特别是 std::memory_order_relaxed 增量与单个线程中常规增量的性能。我不明白为什么 fetch_add(relaxed) 单线程比常规增量慢两倍。

static void BM_IncrementCounterLocal(benchmark::State& state) {
volatile std::atomic_int val2;

while (state.KeepRunning()) {
for (int i = 0; i < 10; ++i) {
DoNotOptimize(val2.fetch_add(1, std::memory_order_relaxed));
}
}
}
BENCHMARK(BM_IncrementCounterLocal)->ThreadRange(1, 8);

static void BM_IncrementCounterLocalInt(benchmark::State& state) {
volatile int val3 = 0;

while (state.KeepRunning()) {
for (int i = 0; i < 10; ++i) {
DoNotOptimize(++val3);
}
}
}
BENCHMARK(BM_IncrementCounterLocalInt)->ThreadRange(1, 8);

输出:

      Benchmark                               Time(ns)    CPU(ns) Iterations      ----------------------------------------------------------------------      BM_IncrementCounterLocal/threads:1            59         60   11402509                                       BM_IncrementCounterLocal/threads:2            30         61   11284498                                       BM_IncrementCounterLocal/threads:4            19         62   11373100                                       BM_IncrementCounterLocal/threads:8            17         62   10491608      BM_IncrementCounterLocalInt/threads:1         31         31   22592452                                       BM_IncrementCounterLocalInt/threads:2         15         31   22170842                                       BM_IncrementCounterLocalInt/threads:4          8         31   22214640                                       BM_IncrementCounterLocalInt/threads:8          9         31   21889704  

最佳答案

对于 volatile int,编译器必须确保它不会优化掉和/或重新排序变量的任何读/写。

对于 fetch_addCPU 必须采取预防措施确保读取-修改-写入操作是原子的。

这是两个完全不同的要求:原子性要求意味着 CPU 必须与您机器上的其他 CPU 通信,确保它们不会在自己的读取和写入之间读取/写入给定的内存位置。如果编译器使用比较和交换指令编译 fetch_add,它实际上会发出一个短循环以捕获其他 CPU 修改其间值的情况。

对于 volatile int 不需要这样的通信。相反,volatile 要求编译器不发明任何读取:volatile 设计用于与硬件寄存器的单线程通信,其中读取值的行为可能具有副作用。

关于c++ - atomic fetch_add 与添加性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34660376/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com