perl 计算硬盘利用率, 以%来查看硬盘资源是否存在IO消耗cpu资源情况;
部份代码参考了iostat源码;
#!/usr/bin/perl use Time::HiRes qw(gettimeofday); use POSIX; $SLEEPTIME=3; sub getDiskUtl() { $clock_ticks = POSIX::sysconf( &POSIX::_SC_CLK_TCK ); # ========= get start time =============== ($start_sec,$start_usec) = gettimeofday; # ========== 在计时开始时,取出操作时间 my $tot_ticks_0 = `grep "0 sda" /proc/diskstats | awk '{print /$13}'`; sleep($SLEEPTIME); #for(1..$SLEEPTIME*1000000){} # ========= get end time =============== ($end_sec,$end_usec) = gettimeofday; # ========== 在计时结束时,再取出一次操作时间 my $tot_ticks_1 = `grep "0 sda" /proc/diskstats | awk '{print /$13}'`; if ($end_usec < $start_usec) { $time_used = (($end_sec - $start_sec - 1)*1e6 + ($end_usec+1e6 - $start_usec)) / 1e3; # Microseconds = Millisecond * 10e3; } else { $time_used = (($end_sec - $start_sec)*1e6 + ($end_usec - $start_usec)) / 1e3; # Microseconds = Millisecond * 1e3 } my $disk_util = ($tot_ticks_1 - $tot_ticks_0)/$time_used*$clock_ticks/10.0; } #printf("/$start_sec is:$start_sec/t /$end_sec is:$end_sec/t/$end_usec is:$end_usec/t/$start_usec is:$start_usec/n"); #printf("/$tot_ticks_1 is %d/t/$tot_ticks_0 is %d /t/$time_used is %d/t/$clock_ticks is %d/n",# $tot_ticks_1,$tot_ticks_0,$time_used,$clock_ticks); printf("%8.8f/%/n",getDiskUtl());