使用宏定义能否实现跨平台的"Sleep"代码?比如:
#ifdef LINUX
#include <header_for_linux_sleep_function.h>
#endif
#ifdef WINDOWS
#include <header_for_windows_sleep_function.h>
#endif
...
Sleep(miliseconds);
...
使用宏定义能否实现跨平台的"Sleep"代码?比如:
#ifdef LINUX
#include <header_for_linux_sleep_function.h>
#endif
#ifdef WINDOWS
#include <header_for_windows_sleep_function.h>
#endif
...
Sleep(miliseconds);
...
#include <chrono>
#include <thread>
...
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
其中ms
是您想要以毫秒为单位休眠的时间量。
您还可以将milliseconds
替换为nanoseconds
,microseconds
,seconds
,minutes
或hours
。(这些是类型std::chrono::duration的特化)。
更新:在C++14中,如果您要休眠一段固定的时间,例如100毫秒,std::chrono::milliseconds(100)
可以写成100ms
。这是由于用户定义字面量的引入,这是在C++11中引入的。在C++14中,chrono
库已扩展以包括以下用户定义字面量:
std::literals::chrono_literals::operator""h
std::literals::chrono_literals::operator""min
std::literals::chrono_literals::operator""s
std::literals::chrono_literals::operator""ms
std::literals::chrono_literals::operator""us
std::literals::chrono_literals::operator""ns
这意味着您可以编写以下内容:
#include <chrono>
#include <thread>
using namespace std::literals::chrono_literals;
std::this_thread::sleep_for(100ms);
请注意,尽管使用using namespace std::literals::chrono_literals
提供了最少量的命名空间污染,但这些运算符也在using namespace std::literals
或using namespace std::chrono
中可用。
有的。你需要将不同的系统休眠调用和包含语句放在你自己的函数中,就像下面这样:
#ifdef LINUX
#include <unistd.h>
#endif
#ifdef WINDOWS
#include <windows.h>
#endif
void mySleep(int sleepMs)
{
#ifdef LINUX
usleep(sleepMs * 1000); // usleep takes sleep time in us (1 millionth of a second)
#endif
#ifdef WINDOWS
Sleep(sleepMs);
#endif
}
然后您的代码调用 mySleep
来睡眠,而不是直接进行系统调用。
int
来表示 mySleep
?使用 unsigned int
是否更合适呢?毕竟,你不可能睡负数秒! :P - Sebastian Lenartowiczshf301有一个好主意,但是这种方式更好:
#ifdef _WINDOWS
#include <windows.h>
#else
#include <unistd.h>
#define Sleep(x) usleep((x)*1000)
#endif
然后像这样使用:
Sleep(how_many_milliseconds);
获取 Boost。
#include <boost/thread/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
...
boost::this_thread::sleep(boost::posix_time::millisec(milliseconds));
posix_time
被称为chrono
。 - Michael Dorstlong value; /* time in microseconds */
struct timeval tv;
tv.tv_sec = value / 1000000;
tv.tv_usec = value % 1000000;
select(0, NULL, NULL, NULL, &tf);
shf301
回答的评论。 - Mooing Duckstruct timespec req={0},rem={0};
req.tv_sec=(milisec/1000);
req.tv_nsec=(milisec - req.tv_sec*1000)*1000000;
nanosleep(&req,&rem);
#include<chrono>
#include<thread>
int main(){
std::this_thread::sleep_for(std::chrono::milliseconds(x));//sleeps for x milliseconds
std::this_thread::sleep_for(std::chrono::seconds(x));//sleeps for x seconds
std::this_thread::sleep_for(std::chrono::minutes(x));//sleeps for x minutes
std::this_thread::sleep_for(std::chrono::hours(x));//sleeps for x hours.
return 0;
}
<chrono>
。 - chrisstd::this_thread::sleep_for(std::chrono::milliseconds(n))
的方法,它不会消耗任何CPU。 - R. Martinho Fernandeschrono
。这节省了我很多麻烦,谢谢。 - chris<time.h>
。它非常可靠。 - Rontogiannis Aristofanis