简体   繁体   English

为什么在调用std :: async后时间成本为0秒?

[英]Why time cost is 0 seconds after call std::async?

See the following code. 请参阅以下代码。

#include <future>
#include <iostream>
#include <ctime>

int main() 
{
    std::future<int> future = std::async(std::launch::deferred, [](){ 
            std::this_thread::sleep_for(std::chrono::seconds(5));
            return 100;  
        }); 
    std::cout << "waiting...\n";

    clock_t start = clock();
    std::future_status status = future.wait_for(std::chrono::seconds(20));
    std::cout << "result is " << future.get() << std::endl;
    clock_t end = clock();
    std::cout<<"Time Cost : "<< (double)(end-start)/CLOCKS_PER_SEC <<" seconds."<< std::endl;
}

It's very confusing about the execution result. 这对执行结果非常困惑。 Yep, the main thread will wait for only 5 seconds around and then print "100". 是的,主线程只会等待5秒左右,然后打印“100”。 But why "Time Cost" shows 0? 但为什么“时间成本”显示0? The test environment is Cygwin with g++ 4.9.3. 测试环境是Cygwin,带有g ++ 4.9.3。 Then I tested it in VS2013. 然后我在VS2013中测试了它。 The result is 25 seocnds. 结果是25个seocnds。 Strange! 奇怪!

It doesn't show 0 on my machine but a very small value : 0;000156s. 它在我的机器上不显示0但是值非常小:0; 000156s。 But as it measures processor time and your main thread does not consume any cpu (wait is not an active loop), the result is almost 0. 但是当它测量处理器时间并且你的主线程不消耗任何cpu(等待不是活动循环)时,结果几乎为0。

clock() returns processor time spent. clock()返回花费的处理器时间。 It doesn't have any guarantee of advancement whatsoever. 它无法保证任何进步。 If your CPU sleeps, the value returned by it will not be advanced. 如果您的CPU休眠,它返回的值将不会提前。 To measure intervals properly, use clocks from std::chrono , for example, std::chrono::steady_clock . 为了恰当地测量时间间隔,使用从时钟std::chrono ,例如, std::chrono::steady_clock

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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