usr bin perl use strict use warnings use Time HiRes my last_packets_tx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/perl
use strict;
use warnings;
use Time::HiRes;
my $last_packets_tx = -1;
my $last_packets_rx = -1;
my $last_time_check = 0;
my $max_speed = 0;
my $speed_tx;
my $speed_rx;
my $max_speed_tx;
my $max_speed_rx;
my $avg_speed_tx = 0;
my $avg_speed_rx = 0;
my $avg_speed_cnt = 0;
my $iface = exists $ARGV[0] ? $ARGV[0] : 'eth0';
my $t;
my $data;
while (1) {
$data = `ifconfig $iface`;
$t = Time::HiRes::time;
if ($data =~ /RX bytes:(\d+).*?TX bytes:(\d+)/) {
if ($last_packets_rx != -1) {
$speed_rx = ($1 - $last_packets_rx) / (Time::HiRes::time - $last_time_check);
$speed_tx = ($2 - $last_packets_tx) / (Time::HiRes::time - $last_time_check);
$max_speed_rx = $speed_rx > $max_speed_rx ? $speed_rx : $max_speed_rx;
$max_speed_tx = $speed_tx > $max_speed_tx ? $speed_tx : $max_speed_tx;
$avg_speed_tx += $speed_tx;
$avg_speed_rx += $speed_rx;
++$avg_speed_cnt;
system "clear";
printf("tx: %0.4f kb/s\n", ($speed_tx / 1024));
printf("rx: %0.4f kb/s\n", ($speed_rx / 1024));
printf("max tx: %0.4f kb/s\n", ($max_speed_tx / 1024));
printf("max rx: %0.4f kb/s\n", ($max_speed_rx / 1024));
printf("avg tx: %0.4f kb/s\n", (($avg_speed_tx / $avg_speed_cnt) / 1024));
printf("avg rx: %0.4f kb/s\n", (($avg_speed_rx / $avg_speed_cnt) / 1024));
}
$last_time_check = $t;
$last_packets_rx = $1;
$last_packets_tx = $2;
}
sleep(1);
}