linux下的精确wait


源代码:

#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;
    }
}

测试,在2.6内核,迅驰1.6G环境下,精确度大概能到0.00001 s,即10us。

posted @   xiaotie  阅读(1086)  评论(1编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示