C++ | 延时函数
函数 sleep/usleep
unsigned sleep(unsigned seconds);
sleep(33);
void usleep(int micro_seconds);
usleep(23);
void sleep_for(const chrono::duration<_Rep, _Period>& __rtime)
std::this_thread::sleep_for(std::chrono::microseconds(msec_to_delay_randy_));
usleep和sleep都是系统调用,usleep更加精确,不能实现实时延迟(系统调用消耗时间)
头文件
#include <windows.h>
#include <unistd.h>
usleep 源码:
typedef unsigned int useconds_t;
inline int usleep(useconds_t us) {
struct timespec req;
req.tv_sec = (long) (us / 1000000U);
req.tv_nsec = (long)((us % 1000000U)*1000U);
int status = nanosleep(&req,0);
return status ? -1 : 0;
}
sleep_for 源码:
void
__sleep_for(chrono::seconds, chrono::nanoseconds);
template<typename _Rep, typename _Period>
inline void
sleep_for(const chrono::duration<_Rep, _Period>& __rtime)
{
if (__rtime <= __rtime.zero())
return;
auto __s = chrono::duration_cast<chrono::seconds>(__rtime);
auto __ns = chrono::duration_cast<chrono::nanoseconds>(__rtime - __s);
#ifdef _GLIBCXX_USE_NANOSLEEP
__gthread_time_t __ts =
{
static_cast<std::time_t>(__s.count()),
static_cast<long>(__ns.count())
};
while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR)
{ }
#else
__sleep_for(__s, __ns);
#endif
}
boost sleep
如果代码中引用了boost,可以直接调用sleep函数
#include <boost/thread.hpp>
#if defined BOOST_THREAD_USES_DATETIME
inline BOOST_SYMBOL_VISIBLE void sleep(::boost::xtime const& abs_time)
{
sleep(system_time(abs_time));
}
#endif
static inline void sleep(const system_time& xt)
{
this_thread::sleep(xt);
}
自定义函数
#include <time.h>
void delay(int seconds)
{
clock_t start = clock();
clock_t lay = (clock_t)seconds * CLOCKS_PER_SEC;
while ((clock()-start) < lay);
}
void delay(double seconds)
{
double start = clock();
double lay = (double)seconds * CLOCKS_PER_SEC;
while ((clock()-start) < lay);
}
时间单位转换
Reference
>>>>> 欢迎关注公众号【三戒纪元】 <<<<<