Skip to content

Core\Script\ExitReport::memoryPeak

$exitReport->memoryPeak(): int

Core\Script\ExitReport::memoryPeak() returns the most memory the script used while it ran, in bytes. It is the same number Core\Budget::memoryPeak() returns, read once when the script ends.

You read the report inside a function that you added with Core\Script::onExit(). The number is read before the first function runs. Memory that a function uses after that does not change it, so every function gets the same number.

Memory that the script already freed is still part of the peak. A script that loaded a large file and kept only a short summary has a small figure for Core\Budget::memoryHeld() at the end, and a large peak.

The examples below show a peak that includes freed memory, a peak that does not change inside an exit function, and a job that writes its peak in a log line.

Return value

Returns int. The highest number of bytes the script used at one time, read when the script ended. It is read before the first function runs, so memory a function uses does not change it.

Examples

Memory that was already freed

<?nvs
// Shows that the peak includes memory the script freed before it ended.
Core\Script::onExit(fn(Core\Script\ExitReport $report): void => {
// The 4 MiB string is freed now, but the peak still includes it.
// This prints "peak is at least 4 MiB: yes".
echo 'peak is at least 4 MiB: ', $report->memoryPeak() >= 4194304 ? 'yes' : 'no', "\n";
});
string $big = Core\Str::repeat('x', 4194304);
echo 'the string has ', Core\Str::length($big), " bytes\n";
$big = '';
echo "the string is freed\n";
Output
the string has 4194304 bytes
the string is freed
peak is at least 4 MiB: yes

The number does not change in an exit function

<?nvs
// Shows that memory an exit function uses does not change the peak in the report.
Core\Script::onExit(fn(Core\Script\ExitReport $report): void => {
int $before = $report->memoryPeak();
// This function makes an 8 MiB string of its own.
string $copy = Core\Str::repeat('y', 8388608);
echo 'the function made ', Core\Str::length($copy), " bytes\n";
// The report was made before this function ran. This prints "same peak: yes".
echo 'same peak: ', $report->memoryPeak() == $before ? 'yes' : 'no', "\n";
});
echo "the script is done\n";
Output
the script is done
the function made 8388608 bytes
same peak: yes

A log line with the peak

<?nvs
// Shows an import job that checks its peak memory in a log line when it ends.
Core\Script::onExit(fn(Core\Script\ExitReport $report): void => {
// The job held 2 MiB of rows, which is 2097152 bytes.
// This prints "job=import peak-ok=yes".
echo 'job=import peak-ok=', $report->memoryPeak() >= 2097152 ? 'yes' : 'no', "\n";
});
array<string> $rows = [];
int $i = 0;
while ($i < 2) {
$rows[] = Core\Str::repeat('r', 1048576);
$i = $i + 1;
}
echo 'imported ', Core\Arr::count($rows), " rows\n";
Output
imported 2 rows
job=import peak-ok=yes