在c中实现时间延迟
我不知道如何确切地表达这个搜索..所以我没有找到任何东西..:S
我需要在C中实现时间延迟
。例如我想做一些事情,然后等待说 1 分钟,然后继续做事。
这有道理吗?有人可以帮我吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我不知道如何确切地表达这个搜索..所以我没有找到任何东西..:S
我需要在C中实现时间延迟
。例如我想做一些事情,然后等待说 1 分钟,然后继续做事。
这有道理吗?有人可以帮我吗?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(17)
尝试
sleep(int number_of_seconds)
Try
sleep(int number_of_seconds)
sleep(int)
可以起到很好的延迟作用。一分钟:sleep(int)
works as a good delay. For a minute:是
定时器
吗?对于 WIN32,请尝试 http://msdn.microsoft.com/ en-us/library/ms687012%28VS.85%29.aspx
Is it
timer
?For WIN32 try http://msdn.microsoft.com/en-us/library/ms687012%28VS.85%29.aspx
你可以简单地调用delay()函数。因此,如果您想将进程延迟 3 秒,请调用delay(3000)...
you can simply call delay() function. So if you want to delay the process in 3 seconds, call delay(3000)...
如果您确定要等待并且永远不会被打断,请在 POSIX 中使用 sleep 或在 Windows 中使用 Sleep。在 POSIX 中,睡眠需要以秒为单位的时间,因此如果您希望时间更短,可以使用像
usleep()
这样的变体,它使用微秒。 Windows 中的睡眠需要几毫秒,您很少需要比这更细的粒度。您可能希望等待一段时间,但又希望允许中断,也许是在紧急情况下。睡眠可以被信号中断,但在这种情况下有更好的方法。
因此,我实际上在实践中发现您所做的就是等待具有超时的事件或条件变量。
在 Windows 中,您的调用是
WaitForSingleObject
。在 POSIX 中,它是pthread_cond_timedwait
。在 Windows 中,您还可以使用
WaitForSingleObjectEx
,然后您可以通过调用QueueUserAPC
实际上“中断”线程并执行任何排队任务。 WaitForSingleObject(Ex) 将返回一个代码来确定它退出的原因,因此当它返回“TIMEDOUT”状态时您就会知道它确实超时了。当您希望它终止时,您可以设置它正在等待的事件。使用
pthread_cond_timedwait
,您可以用信号广播条件变量。 (如果多个线程正在等待同一个线程,则需要广播来唤醒所有线程)。每次循环时都应该检查条件。您的线程可以获取当前时间并查看它是否已经过去,或者可以查看是否满足某些条件来确定要做什么。如果您有某种队列,您可以检查一下。 (您的线程将自动锁定一个互斥锁,用于等待条件变量,因此当它检查条件时,它可以单独访问它)。If you are certain you want to wait and never get interrupted then use sleep in POSIX or Sleep in Windows. In POSIX sleep takes time in seconds so if you want the time to be shorter there are varieties like
usleep()
which uses microseconds. Sleep in Windows takes milliseconds, it is rare you need finer granularity than that.It may be that you wish to wait a period of time but want to allow interrupts, maybe in the case of an emergency. sleep can be interrupted by signals but there is a better way of doing it in this case.
Therefore I actually found in practice what you do is wait for an event or a condition variable with a timeout.
In Windows your call is
WaitForSingleObject
. In POSIX it ispthread_cond_timedwait
.In Windows you can also use
WaitForSingleObjectEx
and then you can actually "interrupt" your thread with any queued task by callingQueueUserAPC
. WaitForSingleObject(Ex) will return a code determining why it exited, so you will know when it returns a "TIMEDOUT" status that it did indeed timeout. You set the Event it is waiting for when you want it to terminate.With
pthread_cond_timedwait
you can signal broadcast the condition variable. (If several threads are waiting on the same one, you will need to broadcast to wake them all up). Each time it loops it should check the condition. Your thread can get the current time and see if it has passed or it can look to see if some condition has been met to determine what to do. If you have some kind of queue you can check it. (Your thread will automatically have a mutex locked that it used to wait on the condition variable, so when it checks the condition it has sole access to it).// 提供延迟x毫秒的ANSI C方法
// Provides ANSI C method of delaying x milliseconds
C11 有一个专门用于此目的的函数:
请注意,该函数仅从 glibc 2.28 开始可用。
C11 has a function specifically for this:
Note that this is only available starting in glibc 2.28.
用于 gcc 中的 C 使用。;
#include
然后使用 Sleep(); /// Sleep() 大写 S。而不是 sleep() 大写 s 。
//Sleep(1000) 是 1 秒 /// 也许。
clang 支持 sleep(),sleep(1) 是 1 秒的时间延迟/等待。
for C use in gcc.
#include <windows.h>
then use Sleep(); /// Sleep() with capital S. not sleep() with s .
//Sleep(1000) is 1 sec /// maybe.
clang supports sleep(), sleep(1) is for 1 sec time delay/wait.
对于 Linux 操作系统上的短暂延迟(例如几微秒),您可以使用“usleep”:
For short delays (say, some microseconds) on Linux OS, you can use "usleep":
写下这段代码:
Write this code :
在标准 C (C99) 中,您可以使用
time()
来执行此操作,例如:顺便说一句,这假设
time()
返回 1 秒分辨率值。我认为标准没有强制要求,因此您可能需要进行调整。为了澄清,这是我所知道的使用 ISO C99 执行此操作的唯一方法(问题仅用“C”标记,这通常意味着便携式解决方案是可取的,尽管,当然,仍然可能会给出特定于供应商的解决方案)。
无论如何,如果您所在的平台提供了更有效的方式,请使用它。正如一些评论所指出的,像这样的紧密循环可能会存在与 CPU 相关的特定问题使用情况和电池寿命。
任何像样的时间切片操作系统都能够降低连续使用其完整时间片的任务的动态优先级,但电池电量可能会出现更多问题。
然而,C 没有指定有关托管环境中操作系统详细信息的任何内容,并且此答案仅适用于 ISO C 和 ISO C(因此不使用
sleep
、select< /code>、Win32 API 调用或类似的东西)。
请记住 POSIX
sleep
可以被信号打断。如果您要走这条路,您需要执行以下操作:In standard C (C99), you can use
time()
to do this, something like:By the way, this assumes
time()
returns a 1-second resolution value. I don't think that's mandated by the standard so you may have to adjust for it.In order to clarify, this is the only way I'm aware of to do this with ISO C99 (and the question is tagged with nothing more than "C" which usually means portable solutions are desirable although, of course, vendor-specific solutions may still be given).
By all means, if you're on a platform that provides a more efficient way, use it. As several comments have indicated, there may be specific problems with a tight loop like this, with regard to CPU usage and battery life.
Any decent time-slicing OS would be able to drop the dynamic priority of a task that continuously uses its full time slice but the battery power may be more problematic.
However C specifies nothing about the OS details in a hosted environment, and this answer is for ISO C and ISO C alone (so no use of
sleep
,select
, Win32 API calls or anything like that).And keep in mind that POSIX
sleep
can be interrupted by signals. If you are going to go down that path, you need to do something like:以下是在大多数桌面系统上执行此操作的方法:
以下是在没有计时器的微型计算机/处理器上执行此操作的方法:
等待循环变量必须进行微调,这些变量对于我的计算机来说工作得非常接近,但是频率范围这使得现代桌面系统变得非常不精确;所以不要在那里使用,除非你是裸露的金属并且不做这样的事情。
Here is how you can do it on most desktop systems:
Here is how you can do it on a microcomputer / processor w/o timer:
The waitloop variables must be fine tuned, those did work pretty close for my computer, but the frequency scale thing makes it very imprecise for a modern desktop system; So don't use there unless you're bare to the metal and not doing such stuff.
检查 sleep(3) 手册页 或 MSDN for Sleep
Check sleep(3) man page or MSDN for Sleep
尽管许多实现都有
time
函数返回当前时间时间以秒为单位,不能保证每个实现都会这样做(例如,有些可能返回毫秒而不是秒 >)。因此,更便携的解决方案是使用difftime
函数。C 标准保证
difftime
返回两个time_t
值之间的时间差(以秒为单位)。因此,我们可以编写一个可移植的时间延迟函数,它将在C 标准的所有兼容实现上运行。关于
time
和difftime
函数的一个警告是,C 标准从未指定粒度。大多数实现的粒度为一秒。虽然这对于持续几秒的延迟来说是可以的,但对于持续一秒的延迟,我们的延迟函数可能会等待太长时间。有一个可移植的标准 C 替代方案:
clock
函数。clock
函数解决方案与我们的time
函数解决方案非常相似:在这种情况下有一个类似于
time
和的警告difftime
:时钟函数的粒度留给实现。例如,具有 32 位clock_t
值且分辨率以微秒为单位的机器可能最终会在 2147 秒后包装clock
返回的值(约36分钟)。因此,考虑使用延迟函数的
time
和difftime
实现来实现持续至少一秒的延迟,以及clock< /code> 延迟持续一秒的实现。
最后要注意的是:
clock
返回处理器时间而不是日历时间;时钟
可能与实际经过的时间不符(例如,如果进程休眠)。Although many implementations have the
time
function return the current time in seconds, there is no guarantee that every implementation will do so (e.g. some may return milliseconds rather than seconds). As such, a more portable solution is to use thedifftime
function.difftime
is guaranteed by the C standard to return the difference in time in seconds between twotime_t
values. As such we can write a portable time delay function which will run on all compliant implementations of the C standard.One caveat with the
time
anddifftime
functions is that the C standard never specifies a granularity. Most implementations have a granularity of one second. While this is all right for delays lasting several seconds, our delay function may wait too long for delays lasting under one second.There is a portable standard C alternative: the
clock
function.The
clock
function solution is quite similar to ourtime
function solution:There is a caveat in this case similar to that of
time
anddifftime
: the granularity of theclock
function is left to the implementation. For example, machines with 32-bit values forclock_t
with a resolution in microseconds may end up wrapping the value returned byclock
after 2147 seconds (about 36 minutes).As such, consider using the
time
anddifftime
implementation of the delay function for delays lasting at least one second, and theclock
implementation for delays lasting under one second.A final word of caution:
clock
returns processor time rather than calendar time;clock
may not correspond with the actual elapsed time (e.g. if the process sleeps).对于长达一分钟的延迟,
sleep()
是一个不错的选择。如果有一天,您想要在小于一秒的延迟上暂停,您可能需要考虑超时的
poll()
。两者都是 POSIX。
For delays as large as one minute,
sleep()
is a nice choice.If someday, you want to pause on delays smaller than one second, you may want to consider
poll()
with a timeout.Both are POSIX.
C11 之前的 C 标准库中没有
sleep()
函数,但 POSIX 确实提供了一些选项。POSIX 函数
sleep()
(unistd.h) 需要一个unsigned int
参数,表示所需睡眠的秒数。尽管这不是标准库函数,但它被广泛使用,并且即使在使用--std=c11
等更严格的设置进行编译时,glibc 似乎也支持它。POSIX 函数
nanosleep()
( time.h) 将两个指向 timespec 结构的指针作为参数,并提供对睡眠持续时间的更精细的控制。第一个参数指定延迟持续时间。如果第二个参数不是空指针,则它保存调用被信号处理程序中断时剩余的时间。使用
nanosleep()
函数的程序可能需要包含 功能测试宏以便编译。当我使用典型的编译器调用gcc -std=c11 -Wall -Wextra -Wpedantic
时,如果没有功能测试宏,以下代码示例将无法在我的 Linux 系统上进行编译。POSIX 曾经有一个
usleep()
函数(unistd. h) 使用useconds_t
参数来指定睡眠持续时间(以微秒为单位)。当与严格的编译器设置一起使用时,该函数还需要一个功能测试宏。唉,usleep()
已随 POSIX.1-2001 废弃,不应再使用。建议现在使用nanosleep()
而不是usleep()
。附录:
C11 确实有标头
threads.h
提供thrd_sleep()
,其工作方式与nanosleep()
相同。直到 2018 年,随着 threads.h >glibc 2.28。一般来说,很难找到支持threads.h
的实现(Clang 很长一段时间都不支持它,但我不确定那里的当前状况)。您必须小心使用此选项。There are no
sleep()
functions in the pre-C11 C Standard Library, but POSIX does provide a few options.The POSIX function
sleep()
(unistd.h) takes anunsigned int
argument for the number of seconds desired to sleep. Although this is not a Standard Library function, it is widely available, and glibc appears to support it even when compiling with stricter settings like--std=c11
.The POSIX function
nanosleep()
(time.h) takes two pointers totimespec
structures as arguments, and provides finer control over the sleep duration. The first argument specifies the delay duration. If the second argument is not a null pointer, it holds the time remaining if the call is interrupted by a signal handler.Programs that use the
nanosleep()
function may need to include a feature test macro in order to compile. The following code sample will not compile on my linux system without a feature test macro when I use a typical compiler invocation ofgcc -std=c11 -Wall -Wextra -Wpedantic
.POSIX once had a
usleep()
function (unistd.h) that took auseconds_t
argument to specify sleep duration in microseconds. This function also required a feature test macro when used with strict compiler settings. Alas,usleep()
was made obsolete with POSIX.1-2001 and should no longer be used. It is recommended thatnanosleep()
be used now instead ofusleep()
.Addendum:
C11 does have the header
threads.h
providingthrd_sleep()
, which works identically tonanosleep()
. GCC did not supportthreads.h
until 2018, with the release of glibc 2.28. It has been difficult in general to find implementations with support forthreads.h
(Clang did not support it for a long time, but I'm not sure about the current state of affairs there). You will have to use this option with care.