C++: How to sleep for a nanosecond?
Solution 1
You should also notice that there is the scheduler, which probably allows no sleeps that are shorter than an timeslice (somewhat around 4 ms - 10 ms, depending on your windows and machine). sleeping less than that is not possible on
Here are some (quite old) research on that issue windows.
This article suggests using Win32 timeBeginPeriod()
to achieve that.
Solution 2
Using C++11
#include <chrono>
#include <thread>
...
std::this_thread::sleep_for(std::chrono::nanoseconds(1));
Note that the implementation may sleep longer than the given period.
![SmRndGuy](https://i.stack.imgur.com/FMjfI.jpg?s=256&g=1)
SmRndGuy
Updated on July 29, 2022Comments
-
SmRndGuy almost 2 years
Possible Duplicate:
Sleep Less Than One MillisecondHow can I make a program sleep for a nanosecond? I searched the Internet, and I found several ways to sleep, but:
windows.h'sSleep()
sleeps only for milliseconds.
ctime
'snanosleep()
is only for POSIX systems, and I'm using Windows.
I also tried this:int usleep(long usec) { struct timeval tv; tv.tv_sec = usec/1000000L; tv.tv_usec = usec%1000000L; return select(0, 0, 0, 0, &tv); };
But Code::Blocks says:
obj\Release\main.o:main.cpp|| undefined reference to `select@20'|
I tried many things, but everything failed. What should I do?