简体   繁体   中英

Does c/c++ have a delay function?

c / c ++是否具有延迟/等待/睡眠功能?

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.

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.

Depends on the platform. There're sleep() and usleep() for instance.

sleep()? Dunno, just an idea.

啊哈,你可以在Windows中使用Sleep()。它是一个内核函数,在Linux中是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);

There is no cross platform solution. sleep() is POSIX, not standard C/C++.

You could look at a cross platform library that provides sleep , eg SDL .

Source code .

For cross platform you can design your own Sleep function. See the example below -

MyClass::MySleepMethod(int milisec)
{
 #ifdef WINDOWS
 Sleep(milisec);
 #else
 sleep(milisec);
 #endif
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM