boost :: asio :: steady_timer()vs sleep()我应该使用哪一个? [英] boost::asio::steady_timer() vs sleep() which one should I use?

查看:427
本文介绍了boost :: asio :: steady_timer()vs sleep()我应该使用哪一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从运行时间的角度来看,以下两个程序相同,均等待5秒钟才能继续.一个使用boost :: asio :: steady_timer,另一个使用sleep(),哪个更好?

The following two program are same from run time point of view, both waiting for 5 seconds to continue. One uses boost::asio::steady_timer, another uses sleep(), which one is better?

1)使用sleep()

1) Use sleep()

$ cat b.cpp
#include <iostream>
#include <unistd.h>

int main(void)
{
    std::cout << "start" << std::endl;
    sleep(5);
    std::cout << "end" << std::endl;
}

$ g++ b.cpp && ./a.out
start
end

2)使用boost :: asio :: steady_timer

2) Use boost::asio::steady_timer

$ cat c.cpp
#include <iostream>
#include <boost/asio.hpp>

int main(void)
{
    std::cout << "start" << std::endl;
    boost::asio::io_context io;
    boost::asio::steady_timer t(io, boost::asio::chrono::seconds(5));
    t.wait();
    std::cout << "end" << std::endl;
    return 0;
}

$ g++ c.cpp -lpthread -lboost_system && ./a.out
start
end

推荐答案

1)

sleep(5)

  • meh:依赖于unistd.h标头,它是非标准且特定于posix的,可能会或可能不会出现问题,但需要考虑
  • con:仅需整数,因此您无法选择亚秒级睡眠,并且可能不清楚这表示5秒,而不是其他单位.
    • meh: relies on the unistd.h header, which is nonstandard and posix-specific, which may or may not be a problem, but is something to consider
    • con: only takes integer so you don't have the option to sleep for sub-seconds, and can be unclear that it means 5 seconds and not some other unit.
    • 2)

      boost::asio::io_context io;
      boost::asio::steady_timer t(io, boost::asio::chrono::seconds(5));
      t.wait();
      

      • meh:依赖于boost,如果您已经包含另一个boost库,这不是问题,但仅出于此目的会显得过分
      • con:取决于io_context
      • pro:使用boost::asio::chrono定义睡眠时间,可以使您更细腻,更清晰
        • meh: relies on boost, not a problem if you're already including another boost library, but would be overkill just for this purpose
        • con: depends on an io_context
        • pro: uses boost::asio::chrono for defining the time to sleep which can give you more granularity and more clarity
        • 3)

          std::this_thread::sleep_for(std::chrono::seconds(5));
          

          • pro:标准库函数(C ++ 11及更高版本)
          • pro:使用std::chrono定义睡眠时间,可以使您更细腻,更清晰
            • pro: standard library function (C++11 and up)
            • pro: uses std::chrono for defining the time to sleep which can give you more granularity and more clarity
            • 注意:如果您是C ++ 11之前的版本,boost也有 this_thread::sleep_for

              这篇关于boost :: asio :: steady_timer()vs sleep()我应该使用哪一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆