Skip to content

Instantly share code, notes, and snippets.

@marcoceppi
Created May 27, 2012 03:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcoceppi/2802099 to your computer and use it in GitHub Desktop.
Save marcoceppi/2802099 to your computer and use it in GitHub Desktop.
<?php
session_start();
$si_prefix = array( 'B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB' );
$base = 1024;
if( !is_array($_SESSION['speed']) )
{
$_SESSION['speed'] = array('updated' => time(), 'old' => file_get_contents('/sys/class/net/eth0/statistics/rx_bytes'));
echo json_encode(array('speed' => '... B/s'));
die();
}
$old = $_SESSION['speed']['old'];
$elapsed = time() - $_SESSION['speed']['updated'];
$current = file_get_contents('/sys/class/net/eth0/statistics/rx_bytes');
$difference = $current - $old;
$diff_per_second = $difference / $elapsed;
$speed = min((int)log($diff_per_second, $base), count($si_prefix) - 1);
$speed = sprintf('%1.2f', $diff_per_second / pow($base, $speed)) . ' ' . $si_prefix[$speed] . '/s';
$_SESSION['speed']['updated'] = time();
$_SESSION['speed']['old'] = file_get_contents('/sys/class/net/eth0/statistics/rx_bytes');
echo json_encode(array('speed' => $speed));
die();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment