HC4*_*ica 1160
在C++ 11中,您可以使用标准库工具执行此操作:
#include <chrono>
#include <thread>
Run Code Online (Sandbox Code Playgroud)
std::this_thread::sleep_for(std::chrono::milliseconds(x));
Run Code Online (Sandbox Code Playgroud)
清晰可读,不再需要猜测sleep()函数采用的单位.
Nie*_*sol 440
请注意,毫秒没有标准的C API,所以(在Unix上)你必须满足usleep,这接受微秒:
#include <unistd.h>
unsigned int microseconds;
...
usleep(microseconds);
Run Code Online (Sandbox Code Playgroud)
MOn*_*DaR 80
为了保持便携性,您可以使用Boost :: Thread进行睡眠:
#include <boost/thread/thread.hpp>
int main()
{
//waits 2 seconds
boost::this_thread::sleep( boost::posix_time::seconds(1) );
boost::this_thread::sleep( boost::posix_time::milliseconds(1000) );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这个答案是重复的,之前已在此问题中发布.也许你也可以找到一些有用的答案.
CB *_*ley 32
您可能拥有usleep或nanosleep可用,具体取决于您的平台.usleep已弃用,已从最新的POSIX标准中删除; nanosleep是优选的.
小智 21
为什么不使用time.h库?在Windows和POSIX系统上运行:
#include <iostream>
#include <time.h>
using namespace std;
void sleepcp(int milliseconds);
void sleepcp(int milliseconds) // Cross-platform sleep function
{
clock_t time_end;
time_end = clock() + milliseconds * CLOCKS_PER_SEC/1000;
while (clock() < time_end)
{
}
}
int main()
{
cout << "Hi! At the count to 3, I'll die! :)" << endl;
sleepcp(3000);
cout << "urrrrggghhhh!" << endl;
}
Run Code Online (Sandbox Code Playgroud)
更正代码 - 现在CPU保持在IDLE状态[2014.05.24]:
#include <iostream>
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif // _WIN32
using namespace std;
void sleepcp(int milliseconds);
void sleepcp(int milliseconds) // Cross-platform sleep function
{
#ifdef _WIN32
Sleep(milliseconds);
#else
usleep(milliseconds * 1000);
#endif // _WIN32
}
int main()
{
cout << "Hi! At the count to 3, I'll die! :)" << endl;
sleepcp(3000);
cout << "urrrrggghhhh!" << endl;
}
Run Code Online (Sandbox Code Playgroud)
Joh*_*ski 17
nanosleep是一个更好的选择usleep- 它更能抵御中断.
小智 14
#include <chrono>
#include <thread>
std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // sleep for 1 second
Run Code Online (Sandbox Code Playgroud)
请记住导入两个标题。
foo*_*bar 13
#include <windows.h>
Run Code Online (Sandbox Code Playgroud)
句法:
Sleep ( __in DWORD dwMilliseconds );
Run Code Online (Sandbox Code Playgroud)
用法:
Sleep (1000); //Sleeps for 1000 ms or 1 sec
Run Code Online (Sandbox Code Playgroud)
从 C++14 使用 std 及其数字文字:
#include <chrono>
#include <thread>
using namespace std::chrono;
std::this_thread::sleep_for(123ms);
Run Code Online (Sandbox Code Playgroud)
小智 7
如果使用MS Visual C++ 10.0,则可以使用标准库工具执行此操作:
Concurrency::wait(milliseconds);
Run Code Online (Sandbox Code Playgroud)
你会需要:
#include <concrt.h>
Run Code Online (Sandbox Code Playgroud)
在具有该select功能的平台(POSIX、Linux 和 Windows)上,您可以执行以下操作:
void sleep(unsigned long msec) {
timeval delay = {msec / 1000, msec % 1000 * 1000};
int rc = ::select(0, NULL, NULL, NULL, &delay);
if(-1 == rc) {
// Handle signals by continuing to sleep or return immediately.
}
}
Run Code Online (Sandbox Code Playgroud)
然而,现在有更好的替代品。