#include "deluge.h" Rate * ratenew(int nticks) { int i; Rate *r; r = emalloc(sizeof r[0]); r->ul = emalloc(sizeof r->ul[0] * nticks); r->dl = emalloc(sizeof r->dl[0] * nticks); r->nticks = nticks; r->i = 0; r->ulcur = 0; r->dlcur = 0; for(i = 0; i < r->nticks; i++) r->ul[i] = r->dl[i] = 0; r->first = time(0); return r; } void rateadd(Rate *r, vlong ul, vlong dl) { r->ul[r->i] += ul; r->ulcur += ul; r->dl[r->i] += dl; r->dlcur += dl; } void ratetick(Rate *r) { r->i = (r->i + 1) % r->nticks; if(r->first + r->nticks <= time(0)){ r->ulcur -= r->ul[r->i]; r->dlcur -= r->dl[r->i]; } r->ul[r->i] = r->dl[r->i] = 0; } vlong ratesum(Rate *r, int nticks, int which) { ulong *p; vlong count; int i; assert(which == Upload || which == Download); p = (which == Upload) ? r->ul : r->dl; assert(nticks <= r->nticks); count = 0; i = r->i; while(nticks > 0){ count += p[i]; i = (i+1) % r->nticks; nticks--; } return count; } double ratecurrent(Rate *r, int nticks, int which) { ulong d; vlong sum; d = MIN(r->nticks, time(0) - r->first); sum = ratesum(r, nticks, which); if(d == 0) return (double)sum; return sum / d; } void ratefree(Rate *r) { free(r->ul); free(r->dl); free(r); }