google / benchmark

A microbenchmark support library
Apache License 2.0
8.88k stars 1.61k forks source link

Multithreaded benchmarks question on iteration count. #1828

Closed mfranzreb closed 1 week ago

mfranzreb commented 1 month ago

As this issue explains, in a multi-threaded benchmark, the threads are synchronized before starting the loop, and after exiting, but not during the iterations. In the following example, the results show that t_1 == t_2. How does this then work? My thought is that the number of iterations is set before the loop starts, is this correct? Is there a built-in functionality to have all threads stop once the first is finished? Thank you for the help!

// 2 threads
for (auto _ : state) {
    if (state.thread_index() == 0) {
      std::this_thread::sleep_for(std::chrono::milliseconds(10));
      ++t_1;
    } else {
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
      ++t_2;
    }
  }
dmah42 commented 3 weeks ago

i'm not sure what your expectations are here. by the end of the run, each thread would have been run the same number of iterations because the iterations are set at the outer loop level.

mfranzreb commented 1 week ago

Hi, thank you for the reply! Just wanted to know if there was a built-in way to have all threads stop executing once the first thread is done. The question is settled now though.