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

前端 未结 8 1159
情歌与酒
情歌与酒 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:39

    Boost.Thread implementation of sleep for POSIX systems can use different approaches to sleeping:

    1. Timed waiting on mutex in case when thread is created with Boost.Thread and has a specific thread information.
    2. Use pthread_delay_np, if available and thread is not created with Boost.Thread.
    3. USe nanosleep if pthread_delay_np is not available.
    4. Create a local mutex and do timed wait on it (worse case scenario if nothing else is available).

    Cases number 2, 3 and 4 are implemented in a loop of 5 times (as of Boost 1.44). So if sleeping thread is interrupted (i.e. with some signal) more than 5 times - there can be a potential problem. But that is not likely to happen.

    In all cases, precision will be much higher than a second, so doing multiple sleeps will not be more precise that doing a long one. You can only be concerned about your program being completely swapped out because of long sleep. For example, if machine is so busy, so kernel puts the whole program on disk. To avoid being swapped out, you have to spin (or do smaller sleeps and wake up occasionally). Usually, if performance matters a lot, programs do spin on a CPU and never call sleep, because any blocking call is to be avoided. But that is true if we are talking nano/micro-seconds.

提交回复
热议问题