Does c/c++ have a delay/wait/sleep function?
The closest to a cross-platform sleep function that I know of is in boost::thread. It's called sleep
.
However, if you're working on a platform where plain ol' sleep(unsigned int seconds)
is available, then I'd just use that.
I asked the mighty google for it and its first answer goes like:
int x,y;
for(x = 0; x < 2000; x++)
{
for(y = 0; y < 2000000; y++)
{
}
}
But you have to adjust the number in for loop to your system.
time_t start_time, cur_time;
time(&start_time);
do
{
time(&cur_time);
}
while((cur_time - start_time) < 3);
and
clock_t start_time, cur_time;
start_time = clock();
while((clock() - start_time) < 3 * CLOCKS_PER_SEC)
{
}
and last but not least
There are several other functions that can be used. For Windows computers, there are _ftime, Sleep(), and QueryPerformanceCounter() functions, as well as the sytem timer.
C++ does not have a sleep function. But most platforms do.
On Linux you have sleep()
and usleep()
. On Windows you have Sleep()
.
You just have to include the appropriate headers to get access to them.
There is no cross platform solution. sleep() is POSIX, not standard C/C++.
You could look at a cross platform library that provides sleep, e.g. SDL.
aha, you can use Sleep() in windows.it's a kernel function, in linux it is sleep(x) x = mil-sec
sleep is not very accurate, as it only give you seconds granularity and your process might not wake up right on the "dot". If you want much more accurate timer. I would use select system call. both unix and windows have it.
Something like this will sleep for 10 microseconds struct timeval tv;
tv.sec = 0;
tv.tv_usec = 10;
select(0,NULL,NULL,NULL,&tv);