复制代码代码如下: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/time.h> #include <sched.h> #define COUNT 1000 #define MILLION 1000000L</p><p>int main(void) { int i; struct timespec slptm; long tdif; struct timeval tend, tstart;</p><p>slptm.tv_sec = 0; slptm.tv_nsec = 1000;//1000 ns = 1 us</p><p>//struct sched_param param; //param.sched_priority = 0; //sched_setscheduler(getpid(), SCHED_FIFO, ¶m);</p><p>if (gettimeofday(&tstart, NULL) == -1) { fprintf(stderr, "Failed to get start time
"); return 1; } for (i = 0; i < COUNT; i++) { if (nanosleep(&slptm, NULL) == -1) { perror("Failed to nanosleep"); return 1; } } if (gettimeofday(&tend, NULL) == -1) { fprintf(stderr, "Failed to get end time
"); return 1; } tdif = MILLION * (tend.tv_sec - tstart.tv_sec) + (tend.tv_usec - tstart.tv_usec); printf("nanosleep() time is %ld us
", tdif/COUNT); return 0; }
HZ 250HZ 时钟中断的时间间隔: 4 ms (1000ms/250) ---------------------------------------- nanosleep() time is 4019 us (4.019 ms) 说明nanosleep的睡眠定时器依赖于时钟中断 HZ 1000HZ 时钟中断的时间间隔: 1 ms ---------------------------------------- nanosleep() time is 12 us 注: 最小睡眠时间为1 us