c – 获取std :: future :: wait_for的已用时间

如果没有发生超时,是否有一种简单的方法可以在std :: future< T> :: wait_for期间获得时间?我想达到这样的目的:

std::future<void> futureRet = std::async(std::launch::async, &Someone::doSomething, this);
futureRet.wait_for(std::chrono::seconds(30));

cout << "doSomething returned after <" << futureRet.getElapsedTime() << "> seconds.";

有一种“getElapsedTime()”函数还是我必须自己计算经过的时间?

最佳答案 使用< chrono>有一种简单的方法:

auto start = std::chrono::steady_clock::now();
std::future<void> futureRet = std::async(std::launch::async, &Someone::doSomething, this);
futureRet.wait_for(std::chrono::seconds(30));
auto end = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;    
cout << "doSomething returned after <" << elapsed_seconds.count() << "> seconds.";
点赞