简体   繁体   English

c / c ++是否具有延迟功能?

[英]Does c/c++ have a delay function?

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

C++ does not have a sleep function. C ++没有睡眠功能。 But most platforms do. 但是大多数平台都可以。

On Linux you have sleep() and usleep() . 在Linux上,您具有sleep()usleep() On Windows you have Sleep() . 在Windows上,您具有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. 我所知道的最接近跨平台的睡眠函数是在boost :: thread中。 It's called sleep . 这就是所谓的sleep

However, if you're working on a platform where plain ol' sleep(unsigned int seconds) is available, then I'd just use that. 但是,如果您正在一个可以使用普通sleep(unsigned int seconds)的平台上工作,那么我将使用它。

Depends on the platform. 取决于平台。 There're sleep() and usleep() for instance. 例如,有sleep()usleep()

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. Unix和Windows都有它。

Something like this will sleep for 10 microseconds struct timeval tv; 像这样的东西将在timeval tv电视中睡眠10微秒;

tv.sec = 0; tv.sec = 0;
tv.tv_usec = 10; tv.tv_usec = 10;
select(0,NULL,NULL,NULL,&tv); select(0,NULL,NULL,NULL,&tv);

There is no cross platform solution. 没有跨平台的解决方案。 sleep() is POSIX, not standard C/C++. sleep()是POSIX,不是标准C / C ++。

You could look at a cross platform library that provides sleep , eg SDL . 您可以看一下提供睡眠的跨平台库,例如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. 但是您必须在for循环中调整系统的数量。

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. 对于Windows计算机,有_ftime,Sleep()和QueryPerformanceCounter()函数以及系统计时器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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