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。

    版权所有,欢迎转载
  • 相关阅读:
    模块二
    lambda map() filter() zip()练习
    装饰器
    函数模块回顾
    连接不同数据OleDb(不完整)
    连接不同的数据库
    连接数据库ORACLE(不完整)
    多数据之间的连接操作ODBC(不完整)
    ora0131
    ORACLE linux 下 sqlplus命令
  • 原文地址:https://www.cnblogs.com/xiaotie/p/325771.html
Copyright © 2011-2022 走看看