以下为封装的获取纳秒,毫秒时间的接口、精确睡眠微秒接口、按照指定频率执行某一个功能的封装和时间转字符串接口。
一、获取时间
text1 2 3 4 5 6 7 8 9 10 11 12 13 14
| /* 获取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; }
|
二、精确睡眠
text1 2 3 4 5 6 7 8 9 10 11
| /* 精确睡眠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 } }
|
三、按照指定频率执行
text1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| 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++;
// 得到从开始到现在的运行总时间;计算睡眠时间 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) { // 用到了上面精确睡眠的函数 sleepUS((do_times_count - do_times_should) * freq_interval_ns - - run_time_ns % freq_interval_ns); } } }
|
四、秒转换为时间字符串
text1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| /* 将时间秒计数转换成 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); }
|
原文链接: https://www.delta1037.cn/2021/C_C++/C-C++时间封装/
版权声明: 转载请注明出处.