有一些延時函數寫法非常佔用CPU,比如while(gettime()>timeSet){},在Linux中應當儘量使用系統調用執行延時,在延時等待期間執行一次進程調度,降低延時函數的CPU佔用率。
Linux中的延時函數有sleep,usleep和nanosleep,以及select。
1、sleep
sleep()調用alarm()來設定報警時間,調用sigsuspend()將進程掛起在信號SIGALARM上。
2、usleep
usleep()有可能會影響信號,用於延遲掛起進程。
3、nanosleep
nanosleep()是Linux系統調用,使進程進入TASK_INTERRUPTIBLE,脫離就緒隊列,然後進行一次進程調度再由內核在規定的時間後發送信號來喚醒這個進程調用進程睡眠,nanosleep()精度不是很高。
4、select
select的精度是微妙,比較精確,將相關參數傳遞給內核。
5、推薦使用的函數
void delayms (unsigned int howLong)
{
struct timespec sleeper, dummy ;
sleeper.tv_sec = (time_t)(howLong / 1000) ;
sleeper.tv_nsec = (long)(howLong % 1000) * 1000000 ;
nanosleep (&sleeper, &dummy) ;
}