源代码:
#include <sys/time.h>
#include <stdio.h>
#include <time.h>
inline double
now()
{
timeval tv;
gettimeofday(&tv, 0);
double s = (tv.tv_sec);
s += (1e-6 * tv.tv_usec);
return s;
}
inline void
wait(double sec)
{
double start_time = now();
const double SLEEP_MIN_TIME = 0.005;
//当等待时间>SLEEP_MIN_TIME时,调用nanosleep() API,避免过多占用内存。
//nanosleep() API的精度约为200us。
if(sec > SLEEP_MIN_TIME)
{
double sleep_time = sec-SLEEP_MIN_TIME;
struct timespec sleep_;
int seconds = static_cast<int>(sleep_time);
sleep_.tv_sec = seconds;
sleep_.tv_nsec = static_cast<int>((sleep_time-seconds)*1e9);
nanosleep(&sleep_,NULL);
}
//开始循环取时,判断时间是否到了。
for(;;)
{
if((now() - start_time) > sec) break;
}
}
#include <stdio.h>
#include <time.h>
inline double
now()
{
timeval tv;
gettimeofday(&tv, 0);
double s = (tv.tv_sec);
s += (1e-6 * tv.tv_usec);
return s;
}
inline void
wait(double sec)
{
double start_time = now();
const double SLEEP_MIN_TIME = 0.005;
//当等待时间>SLEEP_MIN_TIME时,调用nanosleep() API,避免过多占用内存。
//nanosleep() API的精度约为200us。
if(sec > SLEEP_MIN_TIME)
{
double sleep_time = sec-SLEEP_MIN_TIME;
struct timespec sleep_;
int seconds = static_cast<int>(sleep_time);
sleep_.tv_sec = seconds;
sleep_.tv_nsec = static_cast<int>((sleep_time-seconds)*1e9);
nanosleep(&sleep_,NULL);
}
//开始循环取时,判断时间是否到了。
for(;;)
{
if((now() - start_time) > sec) break;
}
}
测试,在2.6内核,迅驰1.6G环境下,精确度大概能到0.00001 s,即10us。