简体   繁体   中英

Is chrono::steady_clock blocking on threads?

I ran into an issue when I wanted to spawn a few threads to do some calculations for a set amount of time. But the total time elapsed is always greater than the sum of each threads allocated time, while I expected it to be more of the maximum. What am I not understanding here?

Some example code:

#include <thread>
#include <chrono>

void do_some_wait(int time);

int main() {
  using std::thread;
  thread t1(&do_some_wait, 1);
  thread t2(&do_some_wait, 1);
  thread t3(&do_some_wait, 1);

  t1.join(); t2.join(); t3.join();
}

void do_some_wait(int time) {
  using std::chrono::steady_clock;
  using std::chrono::seconds;
  auto end = steady_clock::now() + seconds(time);

  while (steady_clock::now() < end) { /* some calculations */ }
}

I'd expect this to take ~1 second to execute. But it takes ~3.

$ clang++ -std=c++11 -stdlib=libc++ -Wall -pedantic thread.cpp -o thread && time ./thread
./thread  2.96s user 0.00s system 295% cpu 1.003 total

The 2.96s user in the output from time is how much CPU time you used. If you run three threads, for one second each, on a processor that has at least three cores [and there isn't much competition from other processes], you are going to use best part of 3 seconds of CPU time. The total time is 1.003s, which is reasonable for a 1s times thread plus a little overhead at start/end.

It takes 1.003 seconds. You did not pay attention to the output, which fulfills your expectations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM