1

Simple usage:

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

int main()
{   
    std::cout << usleep(20 * 1000) << std::endl;

    return 0;
}

Compiled with g++ main.cpp. The executable exit immediately printing 0 indicate no error is detected. So what is wrong?

Jeff Wen
  • 43
  • 1
  • 7
  • 4
    Because that is 20,000 microseconds = .02 seconds. So pretty fast. Can use: unsigned int sleep(unsigned int seconds); instead if you want seconds. – Omid CompSCI Sep 11 '18 at 03:51
  • You should probably define *"wrong"*, but taking it to mean *"too soon"*.... Possible duplicate of [Sleep for milliseconds](https://stackoverflow.com/q/4184468/608639). Maybe related [How to sleep for a few microseconds](https://stackoverflow.com/q/4986818/608639) and several others. – jww Sep 11 '18 at 03:52
  • 1
    Can also view direct manual here: http://man7.org/linux/man-pages/man3/usleep.3.html – Omid CompSCI Sep 11 '18 at 03:53
  • @jww The question might help those whose first language is not English and make same mistake like me. I saw *microsecond* in the man page but I thought it means millisecond. I don't use these two English words that often. So I am gonna keep this question here. – Jeff Wen Sep 11 '18 at 05:10
  • You might encounter the pattern again: no prefix -> seconds, `m` -> milli, `u` -> micro, `n` -> nano; if you wonder why `u` for "micro": because it resembles closest Greek letter mu (μ), standing for - well - micro... – Aconcagua Sep 11 '18 at 05:23

1 Answers1

2

actually the argument you pass to the usleep() is in microseconds. so in 20ms the program is exiting..You can pass 20 *1000000 instead or you can use chrono library.

#include <iostream>       // std::cout, std::endl
#include <thread>         // std::this_thread::sleep_for
#include <chrono>         // std::chrono::seconds

int main() 
{
  std::cout << "countdown:\n";
  for (int i=10; i>0; --i) {
    std::cout << i << std::endl;
    std::this_thread::sleep_for (std::chrono::seconds(1));
  }
  std::cout << "Lift off!\n";

  return 0;
}
Kethiri Sundar
  • 480
  • 2
  • 12