【PHP8.x】memory_reset_peak_usage関数の使い方

memory_reset_peak_usage関数の使い方について、初心者にもわかりやすく解説します。

作成日: 更新日:

基本的な使い方

『memory_reset_peak_usage関数は、PHPが記録しているメモリの最大使用量(ピーク使用量)をリセットする関数です。この関数は、通常memory_get_peak_usage関数と組み合わせて使用されます。PHPはスクリプトの実行開始から、その時点までに消費されたメモリの最大値を内部的に保持しています。memory_reset_peak_usage関数を呼び出すと、この記録されている最大値が、関数を呼び出した時点での現在のメモリ使用量にリセットされます。これにより、スクリプト全体の実行期間ではなく、特定の処理ブロック、例えば重いデータ処理やループ処理といった区間だけで、どれくらいのメモリが最大で消費されたかを正確に計測したい場合に役立ちます。具体的な使用方法として、まず測定したいコードブロックの実行直前にこの関数を呼び出します。その後、対象の処理を実行し、処理が終わった直後にmemory_get_peak_usage関数を呼び出すことで、その特定の区間で消費されたメモリの最大値を取得できます。この関数は引数を取らず、戻り値もありません。メモリ消費のボトルネックを特定したり、コードの最適化を行ったりする際のデバッグツールとして非常に有効です。

構文(syntax)

1memory_reset_peak_usage(): void;

引数(parameters)

引数なし

引数はありません

戻り値(return)

void

この関数は、PHPスクリプトのピークメモリ使用量をリセットします。戻り値はありません。

サンプルコード

PHPでピークメモリ使用量をリセットする

1<?php
2
3/**
4 * Demonstrates the use of memory_get_peak_usage and memory_reset_peak_usage.
5 *
6 * This function shows how to track the highest memory consumption (peak usage)
7 * during script execution and how to reset that peak counter.
8 */
9function demonstrateMemoryResetPeakUsage(): void
10{
11    echo "--- Initial State ---" . PHP_EOL;
12    // Get the initial peak memory usage in bytes.
13    // The 'true' argument requests the real allocated system memory, not just PHP's internal usage.
14    $initialPeak = memory_get_peak_usage(true);
15    echo "Initial Peak Memory Usage: " . $initialPeak . " bytes" . PHP_EOL;
16
17    echo PHP_EOL . "--- First Memory Allocation ---" . PHP_EOL;
18    // Allocate some memory to increase the peak usage.
19    // Creating a large array of strings will consume significant memory.
20    $largeArray1 = array_fill(0, 100000, 'a_long_string_to_take_up_memory_1234567890');
21    // Get peak memory usage after this allocation.
22    $peakAfterFirstAllocation = memory_get_peak_usage(true);
23    echo "Peak Memory Usage after first allocation: " . $peakAfterFirstAllocation . " bytes" . PHP_EOL;
24
25    // Reset the peak memory usage counter.
26    // After this call, memory_get_peak_usage will start tracking a *new* peak
27    // from the current memory usage, ignoring any previous peaks.
28    memory_reset_peak_usage();
29    echo "Peak memory usage has been reset." . PHP_EOL;
30
31    // Get peak memory usage immediately after the reset.
32    // This value will likely be much lower, representing the current memory use,
33    // as the historical peak before the reset has been cleared.
34    $peakAfterReset = memory_get_peak_usage(true);
35    echo "Peak Memory Usage immediately after reset: " . $peakAfterReset . " bytes" . PHP_EOL;
36
37    // Unset the large array to free up its memory.
38    // Note: Freeing memory does not retroactively reduce a recorded peak;
39    // it only affects current and future peak measurements if the peak counter is reset.
40    unset($largeArray1);
41
42    echo PHP_EOL . "--- Second Memory Allocation (after reset) ---" . PHP_EOL;
43    // Allocate more memory after the reset to demonstrate establishing a new peak.
44    $largeArray2 = array_fill(0, 50000, 'another_long_string_to_take_up_memory_abcdefgh');
45    // Get peak memory usage after the second allocation.
46    // This will reflect the new highest usage *since the reset*.
47    $peakAfterSecondAllocation = memory_get_peak_usage(true);
48    echo "Peak Memory Usage after second allocation: " . $peakAfterSecondAllocation . " bytes" . PHP_EOL;
49
50    unset($largeArray2); // Clean up memory used by the second array.
51}
52
53// Execute the demonstration function.
54demonstrateMemoryResetPeakUsage();

PHPのmemory_reset_peak_usage関数は、スクリプト実行中にPHPが使用したメモリの最大値(ピーク値)を記録しているカウンターをリセットする役割を持ちます。この関数は引数を持たず、戻り値もありません(void)。

通常、memory_get_peak_usage()関数は、スクリプトが開始されてから現在までに最も多く消費したメモリ量を返します。しかし、プログラムの特定の区間や処理フェーズごとにメモリ使用量のピークを独立して計測したい場合、これまでのピーク値をリセットする必要があります。

サンプルコードでは、まずmemory_get_peak_usage()で初期のピークメモリ使用量を確認します。次に、大量のメモリを消費する配列を作成し、再びmemory_get_peak_usage()を呼び出すことで、メモリ使用量のピークが上昇したことを示します。ここでmemory_reset_peak_usage()を実行すると、それまでに記録されていたメモリのピーク値がクリアされます。そのため、リセット直後にmemory_get_peak_usage()を呼び出すと、直前の高いピーク値ではなく、リセット時点での現在のメモリ使用量に近い低い値が返されることがわかります。その後、再びメモリを消費する処理を行うと、memory_reset_peak_usage()が呼び出された時点から新たに計測が始まり、その時点以降の新しいピークメモリ使用量が記録されます。

この関数は、プログラムの各フェーズでのメモリ効率を詳細に分析したい場合などに非常に有効です。

memory_reset_peak_usage関数は、これまでに記録された最大のメモリ使用量(ピーク値)をリセットし、呼び出し時点から新たなピーク値を追跡し始めます。これは、特定の処理ブロックにおけるメモリ消費を正確に測定したい場合に特に有用です。本関数は戻り値を持たないため、リセットの成功・失敗を直接検証することはできません。

また、サンプルコードにあるmemory_get_peak_usage(true)は、PHPが使用するメモリだけでなく、システムが割り当てた実メモリ量を取得します。変数をunset()で解放しても、過去に記録されたピーク値が自動的に減少するわけではない点にご留意ください。ピーク値をリセットしない限り、記録されたピーク値はスクリプト終了まで保持されます。

関連コンテンツ

関連プログラミング言語

【PHP8.x】memory_reset_peak_usage関数の使い方 | いっしー@Webエンジニア