1 #ifndef CTRS_H_ 2 #define CTRS_H_ 3 4 /* $FreeBSD$ */ 5 6 #include <sys/time.h> 7 8 /* counters to accumulate statistics */ 9 struct my_ctrs { 10 uint64_t pkts, bytes, events, drop; 11 uint64_t min_space; 12 struct timeval t; 13 }; 14 15 /* very crude code to print a number in normalized form. 16 * Caller has to make sure that the buffer is large enough. 17 */ 18 static const char * 19 norm2(char *buf, double val, char *fmt) 20 { 21 char *units[] = { "", "K", "M", "G", "T" }; 22 u_int i; 23 24 for (i = 0; val >=1000 && i < sizeof(units)/sizeof(char *) - 1; i++) 25 val /= 1000; 26 sprintf(buf, fmt, val, units[i]); 27 return buf; 28 } 29 30 static __inline const char * 31 norm(char *buf, double val) 32 { 33 return norm2(buf, val, "%.3f %s"); 34 } 35 36 static __inline int 37 timespec_ge(const struct timespec *a, const struct timespec *b) 38 { 39 40 if (a->tv_sec > b->tv_sec) 41 return (1); 42 if (a->tv_sec < b->tv_sec) 43 return (0); 44 if (a->tv_nsec >= b->tv_nsec) 45 return (1); 46 return (0); 47 } 48 49 static __inline struct timespec 50 timeval2spec(const struct timeval *a) 51 { 52 struct timespec ts = { 53 .tv_sec = a->tv_sec, 54 .tv_nsec = a->tv_usec * 1000 55 }; 56 return ts; 57 } 58 59 static __inline struct timeval 60 timespec2val(const struct timespec *a) 61 { 62 struct timeval tv = { 63 .tv_sec = a->tv_sec, 64 .tv_usec = a->tv_nsec / 1000 65 }; 66 return tv; 67 } 68 69 70 static __inline struct timespec 71 timespec_add(struct timespec a, struct timespec b) 72 { 73 struct timespec ret = { a.tv_sec + b.tv_sec, a.tv_nsec + b.tv_nsec }; 74 if (ret.tv_nsec >= 1000000000) { 75 ret.tv_sec++; 76 ret.tv_nsec -= 1000000000; 77 } 78 return ret; 79 } 80 81 static __inline struct timespec 82 timespec_sub(struct timespec a, struct timespec b) 83 { 84 struct timespec ret = { a.tv_sec - b.tv_sec, a.tv_nsec - b.tv_nsec }; 85 if (ret.tv_nsec < 0) { 86 ret.tv_sec--; 87 ret.tv_nsec += 1000000000; 88 } 89 return ret; 90 } 91 92 static uint64_t 93 wait_for_next_report(struct timeval *prev, struct timeval *cur, 94 int report_interval) 95 { 96 struct timeval delta; 97 98 delta.tv_sec = report_interval/1000; 99 delta.tv_usec = (report_interval%1000)*1000; 100 if (select(0, NULL, NULL, NULL, &delta) < 0 && errno != EINTR) { 101 perror("select"); 102 abort(); 103 } 104 gettimeofday(cur, NULL); 105 timersub(cur, prev, &delta); 106 return delta.tv_sec* 1000000 + delta.tv_usec; 107 } 108 #endif /* CTRS_H_ */ 109