[英]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.003s,這對於1s線程線程加上開始/結束時的少量開銷是合理的。
這需要1.003秒。 您沒有注意滿足您期望的輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.