Created
October 27, 2011 22:45
-
-
Save eric/1321124 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/perl -w | |
| # | |
| # take a 1 second average of bandwidth | |
| # eric lindvall <[email protected]> | |
| # | |
| use strict; | |
| $| = 1; | |
| my %one = &get_ints (); | |
| sleep 1; | |
| my %two = &get_ints (); | |
| foreach my $i (sort keys %one) | |
| { | |
| if ($one{$i}{"bytes"}{"in"} > 0 && $i ne "lo") | |
| { | |
| my $in_value = prepareValue (($two{$i}{"bytes"}{"in"} - $one{$i}{"bytes"}{"in"}) * 8, 1, 1, 2, " ", "bits/s"); | |
| my $out_value = prepareValue (($two{$i}{"bytes"}{"out"} - $one{$i}{"bytes"}{"out"}) * 8, 1, 1, 2, " ", "bits/s"); | |
| my $total_value = prepareValue ((($two{$i}{"bytes"}{"in"} + $two{$i}{"bytes"}{"out"}) - ($one{$i}{"bytes"}{"in"} + $one{$i}{"bytes"}{"out"})) * 8, 1, 1, 2, " ", "bits/s"); | |
| print "$i:\n"; | |
| print " in: $in_value - " . ($two{$i}{"packets"}{"in"} - $one{$i}{"packets"}{"in"}) . " pps\n"; | |
| print " out: $out_value - " . ($two{$i}{"packets"}{"out"} - $one{$i}{"packets"}{"out"}) . " pps\n"; | |
| print " total: $total_value - " . (($two{$i}{"packets"}{"in"} + $two{$i}{"packets"}{"out"}) - ($one{$i}{"packets"}{"in"} + $one{$i}{"packets"}{"out"})) . " pps\n"; | |
| } | |
| } | |
| sub get_ints | |
| { | |
| my %ret; | |
| open DEV, "< /proc/net/dev" or die "$!"; | |
| while (my $line = <DEV>) { | |
| if ($line =~ /^ *([^:]*): *([^ ]*) *([^ ]*) *([^ ]* *){6}([^ ]*) *([^ ]*) */) { | |
| $ret{$1}{"bytes"}{"in"} = $2; | |
| $ret{$1}{"packets"}{"in"} = $3; | |
| $ret{$1}{"bytes"}{"out"} = $5; | |
| $ret{$1}{"packets"}{"out"} = $6; | |
| } | |
| } | |
| close DEV; | |
| return (%ret); | |
| } | |
| sub prepareValue { | |
| my($value, $dosi, $bytes, $precision, $space, $unit) = @_; | |
| my($prefix) = ""; | |
| if ($dosi) { | |
| ($value, $prefix) = si_unit($value, $bytes); | |
| } | |
| $value = sprintf("%0.${precision}f", $value); | |
| return "$value$space$prefix$unit"; | |
| } | |
| sub si_unit { | |
| my ($value, $bytes) = @_; | |
| my(@symbol) = ('', 'k', 'm', 'G', 'T', 'P', 'E'); | |
| if ($value == 0) | |
| { | |
| return ($value, ''); | |
| } | |
| my $digits = int(log(abs($value))/log(10) / 3); | |
| if ($digits > $#symbol) | |
| { | |
| $digits = $#symbol; | |
| } | |
| my($magfact); | |
| if ($bytes) { | |
| $magfact = 2 ** ($digits * 10); | |
| } else { | |
| $magfact = 10 ** ($digits * 3.0); | |
| } | |
| if ($digits > 0) | |
| { | |
| return ($value/$magfact, $symbol[$digits]); | |
| } else { | |
| return ($value, ''); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment