Are longer sleeps (in C++) less precise than short ones

前端 未结 8 1090
情歌与酒
情歌与酒 2021-01-17 09:06

I have a task to do something every \"round\" minute(at xx:xx:00) And I use something like

const int statisticsInterval=60;
    time_t t=0;
    while (1)
            


        
相关标签:
8条回答
  • 2021-01-17 09:49

    In some threading APIs, it's possible to be awoken before the sleep completes (eg, due to a signal arriving during the sleep). The correct way to handle this is to compute an absolute wake up time, then loop, sleeping for the remaining duration. I would imagine sleeping for one-second intervals to be a hack to approximate this, poorly.

    However, the boost threading API's this_thread::sleep() is not documented to have these early wakeups, and so this technique is not necessary (the boost thread API does the loop for you).

    Generally speaking, there are very few cases where using smaller sleep intervals improves wakeup latency significantly; the OS handles all wakeups more or less the same way. At best, you might keep the cache warm and avoid pageouts, but this would only affect the small portion of memory directly involved in the sleep loop.

    Furthermore, most OSes deal with time using integer counters internally; this means that large intervals do not induce rounding errors (as you might find with floating point values). However, if you are using floating point for your own computation, this may be an issue. If you are currently using floating point intervals (say, a double of seconds since 1970), you may wish to consider integer units (say, a long long of milliseconds since 1970).

    0 讨论(0)
  • 2021-01-17 09:50

    If the goal is to sleep until a given system time (xx:xx:00), consider using the overload of boost::this_thread::sleep that takes a time, as in boost::posix_time::ptime, rather than a duration.

    for example,

    #include <iostream>
    #include <boost/date_time.hpp>
    #include <boost/thread.hpp>
    int main()
    {
        using namespace boost::posix_time;
        ptime time = boost::get_system_time();
        std::cout << "time is " << time << '\n';
        time_duration tod = time.time_of_day();
        tod = hours(tod.hours()) + minutes(tod.minutes() + 1);
        time = ptime(time.date(), tod);
        std::cout << "sleeping to  " << time << "\n";
        boost::this_thread::sleep(time);
        std::cout << "now the time is " << boost::get_system_time() << '\n';
    }
    

    in C++0x these two overloads were given different names: std::this_thread::sleep_for() and std::this_thread::sleep_until();

    0 讨论(0)
提交回复
热议问题