Skip to content

Core\Os::residentBytes

Core\Os::residentBytes(): uint

Returns the most memory this program's process has used so far, in bytes.

The number is the highest point, not the memory in use right now. It never gets smaller, even when the program frees memory. It covers the whole process. A server process adds up every request it has handled, so use Core\Budget for the memory of one request.

Use it to watch a long-running process: put it on a metrics page, or restart a worker when the number gets too large. It is different on every machine, so do not write it into a test.

The examples show how to read the number, that it never gets smaller, and how to put it on a metrics page.

Return value

Returns uint. The most memory the process has used, in bytes.

Errors

  • RuntimeErrorThe operating system did not report the memory of this process.

Examples

Memory used so far

<?nvs
// Shows how to read the most memory this program's process has used so far.
uint $bytes = Core\Os::residentBytes();
// The number is different on every machine, so this example does not print it.
// A running process always uses some memory, so this prints `yes`.
echo $bytes > 0 ? 'yes' : 'no', "\n";
Output
yes

The number never gets smaller

<?nvs
// Shows that the number is the highest point so far. It does not get smaller
// when the program frees memory.
uint $before = Core\Os::residentBytes();
// This builds a text of 20 million characters, and then frees it.
string $big = Core\Str::repeat('x', 20000000);
$big = '';
// The process used more memory while the text existed. That peak is kept, so
// the new number is at least as large as the first one. This prints `yes`.
echo Core\Os::residentBytes() >= $before ? 'yes' : 'no', "\n";
Output
yes

A line for a metrics page

<?nvs
// Shows how a server reports its memory on a metrics page. A monitoring tool
// reads the page and warns somebody when the number gets too large.
string $line = 'process_peak_memory_bytes ' . Core\Os::residentBytes();
// The line starts with the name of the figure, then a space, then the number.
// This prints `yes`.
echo Core\Str::startsWith($line, 'process_peak_memory_bytes ') ? 'yes' : 'no', "\n";
Output
yes