3

In the below C++ program, I am using the function usleep() to sleep for a 1.5 seconds. I implemented that in 2 equivalent methods as illustrated below:

#include <iostream>
#include <unistd.h>

using namespace std;

int main() {
    //METHOD #1
    cout<<"sleep"<<endl;
    usleep(1500000);
    cout<<"wake up"<<endl;

    //METHOD #2
    cout<<"sleep"<<endl;
    for(int i=0; i<1500000; i++)
        usleep(1);
    cout<<"wake up"<<endl;

    return 0;
}

however the results came as follows:

  • First method: takes exactly 1.5 seconds
  • Second method: takes around 1.5 minutes !

Actually, I will need the second method. According to this Answer, I think I need a more accurate function that usleep(). Could any one help ?

Ahmed Hussein
  • 715
  • 1
  • 15
  • 38

1 Answers1

3

From the documentation (emphasis mine)

The usleep() function suspends execution of the calling thread for (at least) usec microseconds. The sleep may be lengthened slightly by any system activity or by the time spent processing the call or by the granularity of system timers.

So in other words, the reason why it takes longer is because it's now "going to sleep" and "waking up" 1500000 times instead of just once, and with such a short sleep duration, that overhead may be much bigger than the actual microsecond sleep.

Blaze
  • 16,736
  • 2
  • 25
  • 44
  • So, how can I implement method #2 with a more accurate function? – Ahmed Hussein Dec 12 '18 at 13:38
  • 2
    The function is always inaccurate, so if you call it multiple times in a row, those inaccuracies add up. Why do you need the method #2 over the first one? It sounds like there might be a better solution to your problem. – Blaze Dec 12 '18 at 13:46