如何在 C++ 代码中添加延迟。

How to add a delay to code in C++.

我想添加一个延迟,这样第一行将 运行,然后在短暂延迟后第二行将 运行。我是 C++ 的新手,所以我不确定我会怎么做。所以理想情况下,在下面的代码中它会打印 "Loading..." 并等待至少 1-2 秒,然后再次打印 "Loading..." 。目前它会立即打印而不是等待。

cout << "Loading..." << endl;
// The delay would be between these two lines. 
cout << "Loading..." << endl; 

您想要 unistd.h 中的 sleep(unsigned int seconds) 函数。在 cout 语句之间调用此函数。

在 C++ 11 中,您可以使用此线程和 crono 来完成它:

#include <chrono>
#include <thread>
...
using namespace std::chrono_literals;
...
std::this_thread::sleep_for(2s);

在温顿 OS

#include <windows.h>
Sleep( sometime_in_millisecs );   // note uppercase S

在 Unix 基础上 OS

#include <unistd.h>
unsigned int sleep(unsigned int seconds);

#include <unistd.h>
int usleep(useconds_t usec); // Note usleep - suspend execution for microsecond intervals

模拟一个'work-in-progress report',你可以考虑:

// 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

输出:

... 9_8_7_6_5_4_3_2_1_0_

work abandoned after 10,175,240 us

概况:方法'work'没有'finish',但是收到了超时退出的命令。 (测试成功)

代码使用 chrono 和 chrono_literals。