2

当我想生成几个线程在设定的时间内进行一些计算时,我遇到了一个问题。但是经过的总时间总是大于每个线程分配时间的总和,而我预计它会超过最大值。我在这里不明白什么?

一些示例代码:

#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 */ }
}

我希望这需要大约 1 秒的时间来执行。但它需要〜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
4

2 回答 2

1

2.96s user输出中的是time您使用了多少 CPU 时间。如果您在至少具有三个内核的处理器上运行三个线程,每个线程一秒钟[并且与其他进程没有太多竞争],您将使用 3 秒 CPU 时间的最佳部分。总时间为 1.003 秒,这对于 1 秒线程加上开始/结束时的一点开销来说是合理的。

于 2013-07-10T10:25:22.400 回答
0

它需要 1.003 秒。您没有注意输出,这符合您的期望。

于 2013-07-10T10:24:57.830 回答