清单 6. getNetworkStats 子例程
sub getNetworkStats {
my $networkCmd = "/sbin/ifconfig eth0 | grep 'RX bytes'";
$networkCmd = `$networkCmd`;
my $rxBytes = 0;
my $txBytes = 0;
chomp($networkCmd);
for( $networkCmd ){
$rxBytes = substr($_, 19);
$rxBytes = substr($rxBytes,0,index($rxBytes," "));
$txBytes = substr($_, 52);
$txBytes = substr($txBytes,0,index($txBytes," "));
my $bothBytes = $rxBytes + $txBytes;
if( $totalPackets == 0 ){
$totalPackets = $bothBytes;
}else{
# find the difference between measurements, set maximum difference to
# 1Mbit, which works well for `saturated' on a 100Mbit/sec network
# reduce the value by a factor of 10000, which spreads the usage
# nicely over 1-100
my $diffRX = $bothBytes - $totalPackets;
if( $diffRX > 1000000 ){ $diffRX = 1000000 }
$diffRX = ($diffRX / 10000);
$totalPackets = $bothBytes;
return( $diffRX );
}# if not first packet check
}# packet count check
}#getNetworkStats
如果 obtuse 方法接近网卡的负载,则这段代码是简单的。/sbin/ifconfig/eth0 命令的输出将列出收到和传输的所有信息包总数。在网络连接速度为 100Mbit/sec 的测试计算机上,超过 1000,000 个传输或接收信息包的所有情况都被视为完全饱和。该值的范围随后会被调整为 0 到 100 之间的通知速率,并作为电子钢琴通知播放。