Skip to content

Core\Budget::memoryPeak

Core\Budget::memoryPeak(): uint

Returns the largest amount of memory your program has used at any point, in bytes.

Core\Budget::memoryHeld gives you the memory your program is using right now, and that number goes down again when a value is freed. The peak keeps the highest point instead. Work that is already finished is still visible in it. A program that read a large file and kept a short summary of it has a small figure for memoryHeld and a large one for the peak.

Read it at the end of a request to see how close that request came to Core\Budget::memoryLimit. That is how you find the requests that are about to fail.

Good to know: the peak is never lower than what your program is using right now, and nothing your program does can lower it.

Return value

Returns uint. The highest number of bytes this request has used. It is never below what memoryHeld() returns. A program cannot reset it.

Examples

The highest point so far

<?nvs
// Shows the highest amount of memory a program has used. The peak is never
// lower than the memory the program is using right now.
array<string> $report = [];
int $i = 0;
while ($i < 10000) {
$report[] = 'one line of the report';
$i = $i + 1;
}
uint $held = Core\Budget::memoryHeld();
uint $peak = Core\Budget::memoryPeak();
// The program is at its highest point right now, so the two readings are close
// together. This prints "yes".
echo $peak >= $held ? "yes\n" : "no\n";
Output
yes

A spike that is already over

<?nvs
// Shows why the peak is useful. A large list is built and then freed. The
// memory the program is using falls back, and the peak keeps the high point.
array<string> $payload = [];
int $i = 0;
while ($i < 50000) {
$payload[] = 'a row of data from a file';
$i = $i + 1;
}
uint $peak = Core\Budget::memoryPeak();
// The program is finished with the data and frees it.
$payload = [];
// This prints "yes" twice. The program now uses less than its high point, and
// the high point is still the same number.
echo Core\Budget::memoryHeld() < $peak ? "yes\n" : "no\n";
echo Core\Budget::memoryPeak() == $peak ? "yes\n" : "no\n";
Output
yes
yes

How close a request came

<?nvs
// Shows what a web server writes to its log at the end of a request. The peak
// against the limit tells you which requests are close to failing.
array<string> $rows = [];
int $i = 0;
while ($i < 20000) {
$rows[] = 'one order line';
$i = $i + 1;
}
uint $limit = Core\Budget::memoryLimit();
uint $peak = Core\Budget::memoryPeak();
if ($limit == 0) {
// A limit of 0 means this program has no limit, so there is nothing to
// compare the peak with.
echo "peak recorded, no limit set\n";
} else {
// The test asks whether the peak is above four fifths of the limit. This
// program uses very little, so it prints the second line.
echo $peak * 5 > $limit * 4
? "the request came close to its limit\n"
: "the request stayed well under its limit\n";
}
Output
the request stayed well under its limit