//函数原型 int nanosleep(struct timespec *req, struct timespec *rem)//参数列表:// req:要求的睡眠时间// rem:剩余的睡眠时间//返回值:// 0:成功;-1,失败,errno保存错误代码//目的:纳秒级别的延迟int nano_delay(long delay){ struct timespec req, rem; long nano_delay = delay; int ret = 0; while(nano_delay > 0) { rem.tv_sec = 0; rem.tv_nsec = 0; req.tv_sec = 0; req.tv_nsec = nano_delay; if(ret = (nanosleep(&req, &rem) == -1)) { printf("nanosleep failed.\n"); } nano_delay = rem.tv_nsec; }; return ret;}//测试,纳秒级延迟的误差率int main(){ int ret = 0; long delay = 0; struct timespec start, end, interv; for(delay = 1000; delay < 1000*1000; delay+=1000) { curr_time(&start); nano_delay(delay); curr_time(&end); diff(&start, &end, &interv); printf("delay = %ld, real delay = %ld, error = %g.\n", delay, interv.tv_sec * 1000000000 + interv.tv_nsec, (float)(interv.tv_sec * 1000000000 + interv.tv_nsec - delay)/delay ); }}//测试结果:// Duo CPU e8200// Ubuntu 12.10 Kernel 3.4//