How do you add a timed delay to a C++ program?

2019-01-29 22:56发布

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?

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.

标签: c++ time
13条回答
何必那么认真
2楼-- · 2019-01-29 23:17

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

cout<<"Apple\n";
Sleep(3000);
cout<<"Mango";

OUTPUT. above code will print Apple and wait for 3 seconds before printing Mango.

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-29 23:22

Do you want something as simple like

sleep(3);
查看更多
Melony?
4楼-- · 2019-01-29 23:23

Win32: Sleep(milliseconds) is what you what

unix: usleep(microseconds) is what you want.

sleep() only takes a number of seconds which is often too long.

查看更多
贪生不怕死
5楼-- · 2019-01-29 23:24

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.

Some additional information:
http://www.opengroup.org/onlinepubs/000095399/functions/sleep.html

查看更多
淡お忘
6楼-- · 2019-01-29 23:26

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));
}
查看更多
一夜七次
7楼-- · 2019-01-29 23:28

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.

查看更多
登录 后发表回答