zoukankan      html  css  js  c++  java
  • 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。

    版权所有,欢迎转载
  • 相关阅读:
    Flutter 中的基本路由
    BottomNavigationBar 自定义 底部导航条
    StatefulWidget 有状态组件
    flutte页面布局四
    flutter页面布局三
    flutter页面布局二
    设计模式-工厂方法模式
    设计模式-代理模式
    设计模式-装饰模式
    SpringBoot项目部署到服务器上,tomcat不启动该项目
  • 原文地址:https://www.cnblogs.com/xiaotie/p/325771.html
Copyright © 2011-2022 走看看