| 1 |
<?php |
|---|
| 2 |
|
|---|
| 3 |
/** Takes a list of numbers, and calculates the average rate (delta) of change |
|---|
| 4 |
* Greg MacLellan, July 9, 2007 |
|---|
| 5 |
*/ |
|---|
| 6 |
class average_rate_calculator { |
|---|
| 7 |
var $_max_age; |
|---|
| 8 |
var $_values; |
|---|
| 9 |
|
|---|
| 10 |
/** Constructor |
|---|
| 11 |
* @param array A reference to an array to use for storage. This will be populated with key/value pairs that store the time/value, respectively. |
|---|
| 12 |
* Because it is passed by reference, it can be stored externally in a session or database, allowing persistant use of this object |
|---|
| 13 |
* across page loads. |
|---|
| 14 |
* @param int The maximum age of values to store, in seconds |
|---|
| 15 |
*/ |
|---|
| 16 |
function average_rate_calculator(&$storage_array, $max_age) { |
|---|
| 17 |
$this->_max_age = $max_age; |
|---|
| 18 |
if (!is_array($storage_array)) { |
|---|
| 19 |
$storage_array = array(); |
|---|
| 20 |
} |
|---|
| 21 |
$this->_values =& $storage_array; |
|---|
| 22 |
} |
|---|
| 23 |
/** Adds a value to the array |
|---|
| 24 |
* @param float The value to add |
|---|
| 25 |
* @param int The timestamp to use for this value, defaults to now |
|---|
| 26 |
*/ |
|---|
| 27 |
function add($value, $timestamp=null) { |
|---|
| 28 |
if (!$timestamp) $timestamp = time(); |
|---|
| 29 |
$this->_values[$timestamp] = $value; |
|---|
| 30 |
} |
|---|
| 31 |
/** Calculate the average per second value |
|---|
| 32 |
* @return The average value, as a rate per second |
|---|
| 33 |
*/ |
|---|
| 34 |
function average() { |
|---|
| 35 |
$this->_clean(); |
|---|
| 36 |
|
|---|
| 37 |
$avgs = array(); |
|---|
| 38 |
$last_time = false; |
|---|
| 39 |
$last_val = false; |
|---|
| 40 |
foreach ($this->_values as $time=>$val) { |
|---|
| 41 |
if ($last_time) { |
|---|
| 42 |
$avgs[] = ($val - $last_val) / ($time - $last_time); |
|---|
| 43 |
} |
|---|
| 44 |
$last_time = $time; |
|---|
| 45 |
$last_val = $val; |
|---|
| 46 |
} |
|---|
| 47 |
// return the average of all our averages |
|---|
| 48 |
if ($count = count($avgs)) { |
|---|
| 49 |
return array_sum($avgs) / $count; |
|---|
| 50 |
} else { |
|---|
| 51 |
return 'unknown'; |
|---|
| 52 |
} |
|---|
| 53 |
} |
|---|
| 54 |
/** Clean old values out of the array |
|---|
| 55 |
*/ |
|---|
| 56 |
function _clean() { |
|---|
| 57 |
$too_old = time() - $this->_max_age; |
|---|
| 58 |
|
|---|
| 59 |
foreach (array_keys($this->_values) as $key) { |
|---|
| 60 |
if ($key < $too_old) { |
|---|
| 61 |
unset($this->_values[$key]); |
|---|
| 62 |
} |
|---|
| 63 |
} |
|---|
| 64 |
} |
|---|
| 65 |
} |
|---|
| 66 |
|
|---|
| 67 |
?> |
|---|