利用sar linux命令显示,cpu的使用率如下: Linux 2.6.18-92.el5 (qa-lombardi7-10.qa.ebay.com) 11/24/2010 01:42:02 AM CPU %user %nice %system %iowait %steal %idle 01:42:03 AM all 0.00 0.00 0.00 60.30 0.00 39.70 01:42:04 AM all 0.50 0.00 0.50 0.00 0.00 99.00 01:42:05 AM all 0.00 0.00 0.00 0.00 0.00 100.00 01:42:06 AM all 0.00 0.00 0.00 0.00 0.00 100.00 01:42:07 AM all 0.50 0.00 0.00 37.00 0.00 62.50 01:42:08 AM all 0.51 0.00 0.00 28.79 0.00 70.71 Average: all 0.25 0.00 0.08 20.97 0.00 78.70 使用perl来解析该文件,代码如下: 其中包括正则表达式的匹配,抽取,以及根据values值对hash进行排序。 #!/usr/bin/perl open LOG_FILE, "<log.log" or die "can not open the file: log.log"; %cpu_usages; while (<LOG_FILE>) { chomp; if (/^/d{2}:/d{2}:/d{2}/s+/w{2}/s+all/s+/d{1}/./d{2}.*/) { my ( $time, $cpu_usage ) = /(^/d{2}:/d{2}:/d{2})/s+/w{2}/s+all/s+(/d{1}/./d{2}).*/; print "time: " . $time . "cpu usage: " . $cpu_usage . "/n"; $cpu_usages{$time} = $cpu_usage; } } ##while ( ( $key, $value ) = each(%cpu_usages) ) { ## print "key: " . $key . " value: " . $value . "/n"; ##} close LOG_FILE; print "********************/n"; foreach $key ( reverse sort { $cpu_usages{$a} <=> $cpu_usages{$b} } keys %cpu_usages ) { print "$cpu_usages{$key}/n"; }