獲取時間
/* 獲取NS時間 -9 */
static uint64_t getTimeOfNs() {
struct timespec tv;
clock_gettime(CLOCK_REALTIME, &tv);
return tv.tv_sec*1000000000 + tv.tv_nsec;
}
/* 獲取MS時間 -3 */
uint64_t get_time_of_ms()
{
struct timeval tv;
gettimeofday(&tv, 0);
return tv.tv_sec * (uint64_t)1000 + tv.tv_usec / 1000;
}
精確睡眠
/* 精確睡眠US時間 */
static void sleepUS(uint64_t usec){
struct timeval tv;
tv.tv_sec = usec / 1000000UL;
tv.tv_usec = usec % 1000000UL;
errno = 0;
select(0, 0, 0, NULL, &tv);
if (errno != 0){
// error
}
}
按照指定頻率執(zhí)行
int freq_op(int freq)
{
uint64_t freq_interval_ns = uint64_t(1000000000/freq)
uint64_t start_time_ns = getTimeOfNs();
uint64_t do_times_count = 0;
while(true)
{
// do some thing
do_times_count++;
// 得到從開始到現(xiàn)在的運行總時間;計算睡眠時間
uint64_t run_time_ns = getTimeOfNs() - start_time_ns;
uint64_t do_times_should = uint64_t(run_time_ns/freq_interval_ns);
if(do_times_count > do_times_should)
{
// 用到了上面精確睡眠的函數(shù)
sleepUS((do_times_count - do_times_should) * freq_interval_ns - - run_time_ns % freq_interval_ns);
}
}
}
秒轉換為時間字符串
/* 將時間秒計數(shù)轉換成 dd:hh:mm:ss的格式 */
void scaleDownTime(uint64_t s_time, std::string &time)
{
char buffer[128];
int d = 0;
int h = 0;
int m = 0;
int s = 0;
if(s_time >= 3600 * 24){
d = s_time / (3600 * 24);
s_time = s_time % (3600 * 24);
}
if(s_time >= 3600){
h = s_time / 3600;
s_time = s_time % 3600;
}
if(s_time >= 60){
m = s_time / 60;
s_time = s_time % 60;
}
s = s_time;
if(d > 0){
int size = snprintf(buffer, 128, "%dd %02d:%02d:%02d", d, h, m, s);
buffer[size] = '\0';
}else{
int size = snprintf(buffer, 128, "%02d:%02d:%02d", h, m, s);
buffer[size] = '\0';
}
time = std::string(buffer);
}