Contributed by dragonchild
on Sep 27, 2001 at 18:15 UTC
Q&A
> programs and processes
Description: How would I, from within the current process, determine my own memory usage? Answer: Determining memory usage of a process... contributed by rob_au The best method to do this would be to make use of the Proc::ProcessTable module which provides access to the Unix process table in a consistent fashion, hiding the vagarities of different /proc implementations.
The following documented code will return the total memory usage and the percentage memory utilisation of the current process by iteration through the process table:
#!/usr/bin/perl -w
use strict;
print join("\n", &memusage), "\n";
exit 0;
# memusage subroutine
#
# usage: memusage [processid]
#
# this subroutine takes only one parameter, the process id for
# which memory usage information is to be returned. If
# undefined, the current process id is assumed.
#
# Returns array of two values, raw process memory size and
# percentage memory utilisation, in this order. Returns
# undefined if these values cannot be determined.
sub memusage {
use Proc::ProcessTable;
my @results;
my $pid = (defined($_[0])) ? $_[0] : $$;
my $proc = Proc::ProcessTable->new;
my %fields = map { $_ => 1 } $proc->fields;
return undef unless exists $fields{'pid'};
foreach (@{$proc->table}) {
if ($_->pid eq $pid) {
push (@results, $_->size) if exists $fields{'size'};
push (@results, $_->pctmem) if exists $fields{'pctmem'};
};
};
return @results;
}
Ooohhh, Rob no beer function well without! | Answer: Determining memory usage of a process... contributed by Zaxo On Linux (since h option differs from BSD), my $sz = `ps h -o sz $$`;
Other ps stats can be gotten similarly. It uses the rich ps system call for process stats, see 'man ps'. Perl's $$ variable is the current pid.
Another approach is to root around in the "/proc/$$/" or '/proc/self/' directory.
|
Please (register and) log in if you wish to add an answer
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Outside of code tags, you may need to use entities for some characters:
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|