如何在 C++ 程序中添加定时延迟?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/158585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you add a timed delay to a C++ program?
提问by Matt Pascoe
I am trying to add a timed delay in a C++ program, and was wondering if anyone has any suggestions on what I can try or information I can look at?
我正在尝试在 C++ 程序中添加定时延迟,并且想知道是否有人对我可以尝试的内容或可以查看的信息有任何建议?
I wish I had more details on how I am implementing this timed delay, but until I have more information on how to add a timed delay I am not sure on how I should even attempt to implement this.
我希望我有更多关于我如何实现这个定时延迟的细节,但是在我有更多关于如何添加一个定时延迟的信息之前,我不确定我应该如何尝试实现这个。
采纳答案by Richard Harrison
Win32: Sleep(milliseconds)
is what you what
Win32:Sleep(milliseconds)
就是你什么
unix: usleep(microseconds)
is what you want.
unix:usleep(microseconds)
就是你想要的。
sleep() only takes a number of seconds which is often too long.
sleep() 只需要几秒钟,这通常太长了。
回答by bames53
An updated answer for C++11:
C++11 的更新答案:
Use the sleep_for
and sleep_until
functions:
使用sleep_for
和sleep_until
函数:
#include <chrono>
#include <thread>
int main() {
using namespace std::this_thread; // sleep_for, sleep_until
using namespace std::chrono; // nanoseconds, system_clock, seconds
sleep_for(nanoseconds(10));
sleep_until(system_clock::now() + seconds(1));
}
With these functions there's no longer a need to continually add new functions for better resolution: sleep
, usleep
, nanosleep
, etc. sleep_for
and sleep_until
are template functions that can accept values of any resolution via chrono
types; hours, seconds, femtoseconds, etc.
有了这些功能也不再是一个需要不断为更好地解决增加新的功能:sleep
,usleep
,nanosleep
等sleep_for
,并sleep_until
是可通过接受任何分辨率的值模板函数chrono
类型; 小时、秒、飞秒等
In C++14 you can further simplify the code with the literal suffixes for nanoseconds
and seconds
:
在C ++ 14可以进一步简化与用于文字后缀代码nanoseconds
和seconds
:
#include <chrono>
#include <thread>
int main() {
using namespace std::this_thread; // sleep_for, sleep_until
using namespace std::chrono_literals; // ns, us, ms, s, h, etc.
using std::chrono::system_clock;
sleep_for(10ns);
sleep_until(system_clock::now() + 1s);
}
Note that the actual duration of a sleep depends on the implementation: You can ask to sleep for 10 nanoseconds, but an implementation might end up sleeping for a millisecond instead, if that's the shortest it can do.
请注意,睡眠的实际持续时间取决于实现:您可以要求睡眠 10 纳秒,但实现可能最终睡眠一毫秒,如果这是它可以做到的最短时间。
回答by Samir Talwar
#include <unistd.h>
usleep(3000000);
This will also sleep for three seconds. You can refine the numbers a little more though.
这也将休眠三秒钟。不过,您可以再细化一些数字。
回答by J.J.
Do you want something as simple like
你想要像这样简单的东西吗
sleep(3);
回答by Wedge
Note that this does not guarantee that the amount of time the thread sleeps will be anywhere close to the sleep period, it only guarantees that the amount of time before the thread continues execution will be at least the desired amount. The actual delay will vary depending on circumstances (especially load on the machine in question) and may be orders of magnitude higher than the desired sleep time.
请注意,这并不能保证线程休眠的时间量将接近休眠期,它只能保证线程继续执行之前的时间量至少是所需的量。实际延迟将根据情况(尤其是相关机器上的负载)而有所不同,并且可能比所需的睡眠时间高几个数量级。
Also, you don't list why you need to sleep but you should generally avoid using delays as a method of synchronization.
此外,您没有列出为什么需要睡觉,但通常应该避免使用延迟作为同步方法。
回答by Marcin
Yes, sleep is probably the function of choice here. Note that the time passed into the function is the smallest amount of time the calling thread will be inactive. So for example if you call sleep with 5 seconds, you're guaranteed your thread will be sleeping for at least 5 seconds. Could be 6, or 8 or 50, depending on what the OS is doing. (During optimal OS execution, this will be very close to 5.)
Another useful feature of the sleep function is to pass in 0. This will force a context switch from your thread.
是的,睡眠可能是这里的首选功能。请注意,传递给函数的时间是调用线程处于非活动状态的最短时间。因此,例如,如果您在 5 秒内调用 sleep,您可以保证您的线程将至少休眠 5 秒。可能是 6、8 或 50,具体取决于操作系统在做什么。(在最佳操作系统执行期间,这将非常接近 5。)
sleep 函数的另一个有用功能是传入 0。这将强制从您的线程进行上下文切换。
Some additional information:
http://www.opengroup.org/onlinepubs/000095399/functions/sleep.html
一些附加信息:http:
//www.opengroup.org/onlinepubs/000095399/functions/sleep.html
回答by Mathias Brossard
You can also use select(2) if you want microsecond precision (this works on platform that don't have usleep(3))
如果您想要微秒精度,您也可以使用 select(2) (这适用于没有 usleep(3) 的平台)
The following code will wait for 1.5 second:
以下代码将等待 1.5 秒:
#include <sys/select.h>
#include <sys/time.h>
#include <unistd.h>`
int main() {
struct timeval t;
t.tv_sec = 1;
t.tv_usec = 500000;
select(0, NULL, NULL, NULL, &t);
}
`
`
回答by ARoberts
I found that "_sleep(milliseconds);"
(without the quotes) works well for Win32 if you include the chrono
library
我发现"_sleep(milliseconds);"
(不带引号)如果包含chrono
库,则适用于 Win32
E.g:
例如:
#include <chrono>
using namespace std;
main
{
cout << "text" << endl;
_sleep(10000); // pauses for 10 seconds
}
Make sure you include the underscore before sleep.
确保在睡觉前包括下划线。
回答by Jayesh Rathod
You can try this code snippet:
你可以试试这个代码片段:
#include<chrono>
#include<thread>
int main(){
std::this_thread::sleep_for(std::chrono::nanoseconds(10));
std::this_thread::sleep_until(std::chrono::system_clock::now() + std::chrono::seconds(1));
}
回答by Abhishek Rathore
to delay output in cpp for fixed time, you can use the Sleep() function by including windows.h header file syntax for Sleep() function is Sleep(time_in_ms) as
要将 cpp 中的输出延迟固定时间,您可以使用 Sleep() 函数,方法是将 Sleep() 函数的 windows.h 头文件语法包含为 Sleep(time_in_ms) 作为
cout<<"Apple\n";
Sleep(3000);
cout<<"Mango";
OUTPUT. above code will print Apple and wait for 3 seconds before printing Mango.
输出。上面的代码将打印 Apple 并在打印 Mango 之前等待 3 秒。