如何在Windows下以编程方式确定我的Perl程序的内存使用情况?

Zai*_*aid 2 perl memory-management

我在Windows下使用ActivePerl作为我的Perl脚本,因此我可以通过Windows任务管理器中的"进程"选项卡查看它使用了多少内存.

我觉得这样做很麻烦.还有另一种方法来确定我的Perl程序的内存使用吗?

cha*_*aos 7

一种方法是使用Proc::ProcessTable:

use Proc::ProcessTable;

print 'Memory usage: ', memory_usage(), "\n";

sub memory_usage() {
    my $t = new Proc::ProcessTable;
    foreach my $got (@{$t->table}) {
        next
            unless $got->pid eq $$;
        return $got->size;
    }
}
Run Code Online (Sandbox Code Playgroud)


Cha*_*lie 5

If you're using ActivePerl, some of these solutions won't work. I've cobbled together something I think should work out of the box in ActivePerl, but it hasn't been tested in less than 5.10, so your mileage may vary. As Pax answered, you can get different numbers depending on what you ask for, i.e., MaximumWorkingSetSize vs WorkingSetSize, etc.

use Win32::OLE qw/in/;

sub memory_usage() {
    my $objWMI = Win32::OLE->GetObject('winmgmts:\\\\.\\root\\cimv2');
    my $processes = $objWMI->ExecQuery("select * from Win32_Process where ProcessId=$$");

    foreach my $proc (in($processes)) {
        return $proc->{WorkingSetSize};
    }
}

print 'Memory usage: ', memory_usage(), "\n";
Run Code Online (Sandbox Code Playgroud)