[英]How to add a delay to code in C++.
I want to add a delay so that one line will run and then after a short delay the second one will run. 我想添加一个延迟,以便一条线可以运行,然后在短暂的延迟后第二条线可以运行。 I'm fairly new to C++ so I'm not sure how I would do this whatsoever.
我对C ++相当陌生,所以我不确定我将如何做。 So ideally, in the code below it would print "Loading..." and wait at least 1-2 seconds and then print "Loading..." again.
因此理想情况下,在下面的代码中,它将打印“ Loading ...”并等待至少1-2秒,然后再次打印“ Loading ...”。 Currently it prints both instantaneously instead of waiting.
当前,它同时打印而不是等待打印。
cout << "Loading..." << endl;
// The delay would be between these two lines.
cout << "Loading..." << endl;
in c++ 11 you can use this thread and crono to do it: 在c ++ 11中,您可以使用此线程和crono来做到这一点:
#include <chrono>
#include <thread>
...
using namespace std::chrono_literals;
...
std::this_thread::sleep_for(2s);
In windons OS 在Windows OS中
#include <windows.h>
Sleep( sometime_in_millisecs ); // note uppercase S
In Unix base OS 在Unix基本操作系统中
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
#include <unistd.h>
int usleep(useconds_t usec); // Note usleep - suspend execution for microsecond intervals
to simulate a 'work-in-progress report', you might consider: 为了模拟“正在进行的报告”,您可以考虑:
// start thread to do some work
m_thread = std::thread( work, std::ref(*this));
// work-in-progress report
std::cout << "\n\n ... " << std::flush;
for (int i=0; i<10; ++i) // for 10 seconds
{
std::this_thread::sleep_for(1s); //
std::cout << (9-i) << '_' << std::flush; // count-down
}
m_work = false; // command thread to end
m_thread.join(); // wait for it to end
With output: 输出:
... 9_8_7_6_5_4_3_2_1_0_
... 9_8_7_6_5_4_3_2_1_0_
work abandoned after 10,175,240 us
10,175,240美元后放弃的工作
Overview: The method 'work' did not 'finish', but received the command to abandon operation and exit at timeout. 概述:“工作”方法未“完成”,但收到了放弃操作并在超时时退出的命令。 (a successful test)
(测试成功)
The code uses chrono and chrono_literals. 该代码使用chrono和chrono_literals。
You want the sleep(unsigned int seconds)
function from unistd.h
. 您需要
unistd.h
的sleep(unsigned int seconds)
函数。 Call this function between the cout
statements. 在
cout
语句之间调用此函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.