How to get CPU and memory usage of current Perl process?
Question
How to get CPU and memory usage of current Perl process?
In Perl, obtaining CPU and memory usage of the current process is useful for monitoring and profiling. However, this requires platform-specific system interfaces that aren't always available in sandboxed environments. The most portable core-only approach uses the times built-in function for CPU usage, though memory usage requires platform-specific methods.
Using the times() Built-in Function
Perl's times function returns CPU time information for the current process without requiring file system access. It returns a list of four values: user time, system time, children's user time, and children's system time (all in seconds). This works across Unix-like systems and is part of Perl's core.
Example: Portable CPU Time Measurement
The code below demonstrates using times to get CPU usage and simulates some work to show measurable CPU time:
#!/usr/bin/env perl
use strict;
use warnings;
# Get initial CPU times
my ($user_start, $system_start) = times;
# Simulate some CPU work
my $sum = 0;
for my $i (1..100000) {
$sum += sqrt($i);
}
# Get final CPU times
my ($user_end, $system_end) = times;
# Calculate CPU time used
my $user_time = $user_end - $user_start;
my $system_time = $system_end - $system_start;
my $total_cpu = $user_time + $system_time;
print "Current Perl process PID: $$\n";
printf "User CPU Time: %.4f seconds\n", $user_time;
printf "System CPU Time: %.4f seconds\n", $system_time;
printf "Total CPU Time: %.4f seconds\n", $total_cpu;
print "Calculation result: $sum (to prevent optimization)\n";
Explanation
timesreturns a 4-element list in list context; we capture the first two values (user and system CPU time)- The times are cumulative since process start, measured in seconds (not clock ticks)
$$gives the current process ID- We perform actual computation to ensure measurable CPU time is consumed
Memory Usage Limitations
Unfortunately, getting memory usage in a portable, sandbox-safe way using only core modules is not possible. Memory information requires reading from /proc (Linux), using BSD::Resource (not core), or platform-specific APIs. In restricted environments, you can only reliably measure CPU time with times.
Common Pitfalls
- Resolution: CPU times may show as 0.00 for very quick operations due to timer granularity
- Children processes: The 3rd and 4th values from
timestrack child processes, useful for forking scripts - Context matters: Call
timesin list context; in scalar context it returns only elapsed real time - Memory measurement: Requires platform-specific code or non-core modules like
Memory::Usage
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 19ms
Current Perl process PID: 44683
User CPU Time: 0.0000 seconds
System CPU Time: 0.0000 seconds
Total CPU Time: 0.0000 seconds
Calculation result: 21082008.9739179 (to prevent optimization)
(empty)