c++ 中的sleep 函式
阿新 • • 發佈:2019-02-13
標準庫中無該函式
但在某些編譯系統中有,在有些系統庫中有,要根據你那邊的環境而定。 如:
linux中有,unsigned int sleep(unsigned int seconds),傳入掛起時間,成功返回0,不成功則返回餘下的秒數。 windows系統中有Sleep函式(注意大寫),void Sleep(DWORD dwMilliseconds); 提供掛起的毫秒數。
例如:
#include<iostream> #include<windows.h> using namespace std; int main() { Sleep(3000);//暫停3秒 S要大寫 return 0; }
Use std::this_thread::sleep_for
:
std::chrono::milliseconds timespan(111605);// or whatever
std::this_thread::sleep_for(timespan);
There is also the complimentary std::this_thread::sleep_until
.
Prior to C++11, C++ had no thread concept and no sleep capability, so your solution was necessarily platform dependent. Here's a snippet that defines a sleep
#ifdef _WIN32
#include<windows.h>void sleep(unsigned milliseconds){Sleep(milliseconds);}#else#include<unistd.h>void sleep(unsigned milliseconds){
usleep(milliseconds *1000);// takes microseconds}#endif
But a much simpler pre-C++11 method is to use boost::this_thread::sleep
.