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

如何使用perl脚本在linux中测量特定进程的硬盘性能,perl,Perl,下面是我尝试过的代码,但只有一些条目。例如,我在脚本中使用了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|

下面是我尝试过的代码,但只有一些条目。例如,我在脚本中使用了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'};
}
要按进程ID报告特定进程的信息,只需从命令行将$$替换为另一个PID即可

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

alex@yuzu:~$ ./read_write.pl
Read bytes: 95
Write bytes: 1000000
----------
Read bytes: 103
Write bytes: 1000000
----------
Read bytes: 103
Write bytes: 1000000
#!/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
----------