How can I programmatically determine my Perl program's memory usage under Windows?

前端 未结 4 1705
既然无缘
既然无缘 2020-12-06 08:30

I use ActivePerl under Windows for my Perl script, so I can look at how much memory it uses via the \'Processes\' tab in Windows Task Manager.

I find having to do th

相关标签:
4条回答
  • 2020-12-06 09:01

    WMI is the standard way under Windows to examine this sort of stuff from within a program. I believe you would be looking for this.

    MaximumWorkingSetSize is the value of physical RAM in use. VirtualSize is the size of your total address space in use.

    0 讨论(0)
  • 2020-12-06 09:02

    One way is to use 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;
        }
    }
    
    0 讨论(0)
  • 2020-12-06 09:09

    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";
    
    0 讨论(0)
  • 2020-12-06 09:28

    Try:

    open( STAT , "</proc/$$/stat" )
        or die "Unable to open stat file";
    @stat = split /\s+/ , <STAT>;
    close( STAT );
    

    You can take a look at the "Determining memory usage of a process" and "Determining the Memory Usage of a Perl program from within Perl" on PerlMonks.

    0 讨论(0)
提交回复
热议问题