linux下的精确wait
生活随笔
收集整理的這篇文章主要介紹了
linux下的精确wait
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
源代碼:
#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;????????
????
????//當(dāng)?shù)却龝r(shí)間>SLEEP_MIN_TIME時(shí),調(diào)用nanosleep()?API,避免過(guò)多占用內(nèi)存。
????//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);????????????
????}
????//開始循環(huán)取時(shí),判斷時(shí)間是否到了。
????for(;;)
????{
????????if((now()?-?start_time)?>?sec)?break;
????}
}
測(cè)試,在2.6內(nèi)核,迅馳1.6G環(huán)境下,精確度大概能到0.00001 s,即10us。
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)
總結(jié)
以上是生活随笔為你收集整理的linux下的精确wait的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【go】wire的具体各类用法
- 下一篇: [读书笔记]My Life--Bill