#38 delay_loop with nanosleep can not get high resolution

open
nobody
None
5
2010-07-17
2010-07-17
Kirby Zhou
No

delay_loop with nanosleep can not get high resolution under all platforms.
So iperf's bandwidth control would fail.

For example:

~]# cat delaytest.cpp
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>

void delay_loop(unsigned long usec)
{
struct timespec requested, remaining;

requested.tv_sec = 0;
requested.tv_nsec = usec * 1000L;

while (nanosleep(&requested, &remaining) == -1)
if (errno == EINTR)
requested = remaining;
else {
perror("nanosleep");
break;
}
}

#define PAUSE 170
#define LOOP 50

int main()
{
timeval t, t0;
gettimeofday(&t0, NULL);
int d[LOOP];
for (int i = 0; i < LOOP; ++i) {
delay_loop(PAUSE);
gettimeofday(&t, NULL);
d[i] = t.tv_usec - t0.tv_usec;
t0 = t;
}
for (int i = 0; i < LOOP; ++i) {
printf("%d\t", d[i]);
}
printf("\n");
}

]# ./delaytest
1035 1004 995 999 999 1001 1000 999 1000 1000 1000 999 1000 1000 1000 1000 9991000 1000 1000 999 1000 1001 1000 999 1000 1001 998 1000 1000 1002 998 999 1001001 999 999 1000 1001 999 1000 1000 1000 1000 999 1000 1000 999 1000 1000

]# uname -a
Linux djt_18_4 2.6.18-164.el5 #1 SMP Tue Aug 18 15:51:48 EDT 2009 x86_64 x86_64 x86_64 GNU/Linux

Discussion