分类: LINUX
The nanosleep() function shall cause the current thread to be suspended from execution until either the time interval specified by the rqtp argument has elapsed or a signal is delivered to the calling thread, and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested because the argument value is rounded up to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time shall not be less than the time specified by rqtp, as measured by the system clock CLOCK_REALTIME.
The use of the nanosleep() function has no effect on the action or blockage of any signal.
简单来说,这个误差是与调度器的时间片和调度策略有关的,也就是可以通过减小时间片大小和使用实时性更好的调度策略(比如SCHED_RR)来获得更小的分辨率。
- #include<stdio.h>
- #include<stdlib.h>
- #include<unistd.h>
- #include<sys/time.h>
- #include<sched.h>
- #define COUNT 10000
- #define MILLION 1000000L
- #define NANOSECOND 1000
- int main(int argc,char* argv[])
- {
- int i;
- struct timespec sleeptm;
- long interval;
- struct timeval tend,tstart;
- struct sched_param param;
- if(argc != 2)
- {
- fprintf(stderr,"usage:./test sched_method\n");
- return -1;
- }
- int sched = atoi(argv[1]);
- param.sched_priority = 1;
- sched_setscheduler(getpid(),sched,¶m);
- int scheduler = sched_getscheduler(getpid());
- fprintf(stderr,"default scheduler is %d\n",scheduler);
- sleeptm.tv_sec = 0;
- sleeptm.tv_nsec = NANOSECOND;
- if(gettimeofday(&tstart,NULL)!=0)
- {
- fprintf(stderr,"get start time failed \n");
- return -2;
- }
- for(i = 0;i<COUNT;i++)
- {
- if(nanosleep(&sleeptm,NULL) != 0)
- {
- fprintf(stderr,"the %d sleep failed\n",i);
- return -3;
- }
- }
- if(gettimeofday(&tend,NULL)!=0)
- {
- fprintf(stderr,"get end time failed \n");
- return -4;
- }
- interval = MILLION*(tend.tv_sec - tstart.tv_sec)
- +(tend.tv_usec-tstart.tv_usec);
- fprintf(stderr,"the expected time is %d us,but real time cost is %lu us\n",COUNT,interval);
- return 0;
- }
- root@libin:~/program/C/timer# ./test 0
- default scheduler is 0
- the expected time is 10000 us,but real time cost is 630624 us
- root@libin:~/program/C/timer# ./test 1
- default scheduler is 1
- the expected time is 10000 us,but real time cost is 67252 us
- root@libin:~/program/C/timer# ./test 2
- default scheduler is 2
- the expected time is 10000 us,but real time cost is 82449 us
- #define SCHED_OTHER 0
- #define SCHED_FIFO 1
- #define SCHED_RR 2
- #ifdef __USE_GNU
- # define SCHED_BATCH 3
- #endif