javascript - Calculating bytes per second (the smooth way) -


i looking solution calculate transmitted bytes per second of repeatedly invoked function (below). due inaccuracy, not want divide transmitted bytes elapsed overall time: resulted in inability display rapid speed changes after running few minutes.

the preset (invoked approximately every 50ms):

function uploadprogress(loaded, total){     var bps = ?;     $('#elem').html(bps+' bytes per second'); }; 
  • how obtain average bytes per second (only) last n seconds , idea?
  • what other practices calculating non-flickering precise bps value available?

your first idea not bad, it's called moving average, , providing call update function in regular intervals need keep queue (a fifo buffer) of constant length:

var window_size = 10; var queue = [];  function updatequeue(newvalue) {     // fifo fixed length     queue.push(newvalue);     if (queue.length > window_size)         queue.shift(); }  function getaveragevalue() {      // if queue has less 10 items, decide if want calculate     // average anyway, or return invalid value indicate "insufficient data"      if (queue.length < window_size) {          // don't want throw if queue empty,          // @ least consider returning 'invalid' value in order         // display "calculating..."          return null;     }      // calculate average value     var sum = 0;     (var = 0; < queue.length; i++) {         sum += queue[i];     }     return sum / queue.length; }  // calculate speed , call `updatequeue` every second or var updatetimer = setinterval(..., 1000); 

an simpler way avoid sudden changes in calculated speed use low-pass filter. simple discrete approximation of pt1 filter be:

discrete pt1 filter approximation

where u[k] input (or actual value) @ sample k, y[k] output (or filtered value) @ sample k, , t time constant (larger t means y follow u more slowly).

that translated like:

var speed = null; var time_constant = 5;  function updatespeed(newvalue) {         if (speed === null) {         speed = newvalue;     } else {         speed += (newvalue - speed) / time_constant;     } }  function getfilteredvalue() {     return speed; } 

both solutions give similar results (for purpose @ least), , latter 1 seems bit simpler (and needs less memory).

also, wouldn't update value fast. filtering turn "flickering" "swinging" @ refresh rate of 50ms. don't think expects have upload speed shown @ refresh rate of more once per second (or couple of seconds).


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

mysql - Pass value between different pages (form) with PHP -