如何使用perl脚本测量linux中特定进程的硬盘性能



下面是我尝试过的代码,但只有一些条目在那里。在这里,例如,我在脚本中使用了chrome。是否有其他方法可以找到特定进程的硬盘性能?

my @processes;
@processes=`iotop -b -n 1 | grep chrome`;
my $read_per_second=0;
my $write_per_second=0;
foreach(@processes)
{
    my $read=0;
    my $write=0;
    while ($_ =~ /([d.]+)s+[B|K]/s+s+([d.]+)/sg)
    {
        $read_per_second+=$1;
        $write_per_second+=$2;
    }
}

对于给定的进程,您可以在/proc/[pid]/io中获得当前的I/O统计信息。

如果你从这个文件读了很多次,你可以得到每秒的读和写。

例如:

#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
for (1 .. 3) {
    my ($read_bytes_one, $write_bytes_one) = get_io_stats();
    open(my $fh, '>', '/tmp/foo');
    print $fh "x" x 1_000_000;
    close($fh);
    my ($read_bytes_two, $write_bytes_two) = get_io_stats();
    say "Read bytes: ", $read_bytes_two - $read_bytes_one;
    say "Write bytes: ", $write_bytes_two - $write_bytes_one;
    say "----------";
}

sub get_io_stats {
    open(my $fh_in, '<', "/proc/$$/io");
    my %data;
    while (my $line = readline($fh_in)) {
        if ($line =~ m{^ ( .+? ) : s+ ( d+ ) $}msx) {
            $data{$1} = $2;
        }
    }
    close($fh_in);
    return @data{'rchar', 'wchar'};
}
输出:

alex@yuzu:~$ ./read_write.pl
Read bytes: 95
Write bytes: 1000000
----------
Read bytes: 103
Write bytes: 1000000
----------
Read bytes: 103
Write bytes: 1000000

要使它按进程ID报告特定进程的信息,只需从命令行中将$$替换为另一个PID。

要获得每秒的统计数据,只需在每次读取/proc/[pid]/io之间睡眠一秒钟。

#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
my $PID = $ARGV[0] or die "Usage: $0 'pid'n";
for (1 .. 3) {
    my ($read_bytes_one, $write_bytes_one) = get_io_stats();
    sleep 1;
    my ($read_bytes_two, $write_bytes_two) = get_io_stats();
    say "Read bytes: ", $read_bytes_two - $read_bytes_one;
    say "Write bytes: ", $write_bytes_two - $write_bytes_one;
    say "----------";
}

sub get_io_stats {
    open(my $fh_in, '<', "/proc/$PID/io");
    my %data;
    while (my $line = readline($fh_in)) {
        if ($line =~ m{^ ( .+? ) : s+ ( d+ ) $}msx) {
            $data{$1} = $2;
        }
    }
    close($fh_in);
    return @data{'rchar', 'wchar'};
}

工作原理如下:

alex@yuzu:~$ ./read_write.pl 
Usage: ./read_write.pl 'pid'
alex@yuzu:~$ ./read_write.pl 1806
Read bytes: 0
Write bytes: 444141
----------
Read bytes: 0
Write bytes: 441639
----------
Read bytes: 0
Write bytes: 451647
----------

最新更新