Код:
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
unsigned long long tv_diff(struct timeval *tv1, struct timeval *tv2) {
unsigned long long ret;
ret = ((unsigned long long)(tv2->tv_sec - tv1->tv_sec)) * 1000000ULL;
if (tv2->tv_usec > tv1->tv_usec)
ret += (tv2->tv_usec - tv1->tv_usec);
else
ret -= (tv1->tv_usec - tv2->tv_usec);
return ret;
}
main(int argc, char **argv) {
struct timeval tv1, tv2, tv3, tv4, wait;
int loops;
if (argc > 1)
loops = atol(argv[1]);
else
loops = 100000;
memset(&tv1, 0, sizeof(tv1)); memset(&tv2, 0, sizeof(tv2));
memset(&tv3, 0, sizeof(tv3)); memset(&tv4, 0, sizeof(tv4));
printf("Date_sec.msec select loop maxlat nbmax\n");
gettimeofday(&tv1, NULL);
while (1) {
int i, max, times;
gettimeofday(&tv2, NULL);
tv4 = tv2;
max = 0; times = 0;
do {
gettimeofday(&tv3, NULL);
i = tv_diff(&tv4, &tv3);
if (i > max)
max = i;
if (i > 10000)
times++;
tv4 = tv3;
i = tv_diff(&tv2, &tv3);
} while (i < loops);
printf("%lu.%03lu %7lld %7lld %7d %7d\n",
tv3.tv_sec, tv3.tv_usec/1000,
tv_diff(&tv1, &tv2), tv_diff(&tv2, &tv3),
max, times);
wait.tv_sec = 0;
wait.tv_usec = 1000;
gettimeofday(&tv1, NULL);
select(0, NULL, NULL, NULL, &wait);
}
}