是线程上的chrono::steady_clock阻塞
Is chrono::steady_clock blocking on threads?
当我想生成几个线程来在一定的时间内进行一些计算时,我遇到了一个问题。但是,所用的总时间总是大于每个线程分配的时间之和,而我预计它会超过最大值。我在这里不明白什么?
一些示例代码:
#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
time
输出中的2.96s user
是您使用的CPU时间。如果您在一个至少有三个内核的处理器上运行三个线程,每个线程一秒钟(并且没有来自其他进程的太多竞争),您将使用3秒钟的CPU时间。总时间为1.003秒,这对于1次线程加上开始/结束时的一点开销来说是合理的。
需要1.003秒。您没有注意到输出,这满足了您的期望。
相关文章:
- 使用 SendInput 或 mouse_event 不适用于 clock()?
- 将 boost:::chrono::steady_clock::time_point 转换为标准::时间::steady
- 为什么我们可以在 c++ 中使用 srand(clock())?
- 除了使用 clock() 函数之外,有没有更好的方法来以给定的频率生成/发布数据
- IBM AIX std::clock()?
- 为什么常量CLOCKS_PER_SEC不需要用 std:: 命名,但 <ctime> clock() 和 clock_t 可以呢?
- 当我使用 cin 时,我如何使用 clock() 测量时间
- 'clock()' 给出通常的时钟而不是 CPU 时钟
- 使用Clock()函数测量程序的运行时间
- 为什么我的sf :: clock在sfml中单独重置
- C++:Linux 中的计时(使用 clock())不同步(由于 OpenMP?)
- 如何在Linux上获得C 代码块的时钟刻度?clock()结果没有意义
- clock :: getElapSedTime()被调用时SFML 2.0崩溃
- 为什么在使用基于 clock() 的计时器宏时会得到负值
- clock() 函数始终返回 0
- 使用 clock() 函数调度任务时出现问题
- C++ VMWare Fusion/Boot Camp 下 VS2010 中 ctime 的 clock() 方法出现问题
- 为什么clock()被认为是坏的
- MFC/C++:需要遥远的"wall clock"时间而不重置系统的时间
- c++ 中的 clock() 时间和 java 中的 System.CurrentTimeMillis() 之间的时间差