PHPでWebアプリケーションのパフォーマンスを向上させる際に欠かせないのがOPcacheです。そして、そのOPcacheの状態を詳細に把握するために使用するのが opcache_get_status
関数です。
この記事では、opcache_get_status
関数の基本的な使い方から実践的な活用方法まで、初心者にも分かりやすく解説していきます。
opcache_get_status関数とは?
opcache_get_status
は、PHPのOPcache拡張モジュールが提供する関数で、OPcacheの現在の状態や統計情報を取得することができます。
基本的な構文
opcache_get_status(bool $include_scripts = true): array|false
パラメータ:
$include_scripts
: キャッシュされたスクリプトの詳細情報を含めるかどうか(デフォルト: true)
戻り値:
- 配列: OPcacheの状態情報
- false: OPcacheが無効または利用できない場合
実際に使ってみよう
最もシンプルな使用例から見ていきましょう。
<?php
// OPcacheの状態を取得
$status = opcache_get_status();
if ($status === false) {
echo "OPcacheは利用できません";
} else {
echo "OPcacheは正常に動作しています";
print_r($status);
}
?>
取得できる情報の詳細
opcache_get_status
で取得できる情報は非常に豊富です。主要な項目を見ていきましょう。
1. 基本的なステータス情報
<?php
$status = opcache_get_status();
echo "OPcacheは有効か: " . ($status['opcache_enabled'] ? 'はい' : 'いいえ') . "\n";
echo "キャッシュフルか: " . ($status['cache_full'] ? 'はい' : 'いいえ') . "\n";
echo "再起動が保留中か: " . ($status['restart_pending'] ? 'はい' : 'いいえ') . "\n";
echo "再起動が進行中か: " . ($status['restart_in_progress'] ? 'はい' : 'いいえ') . "\n";
?>
2. メモリ使用状況
<?php
$status = opcache_get_status();
$memory = $status['memory_usage'];
echo "使用中メモリ: " . number_format($memory['used_memory'] / 1024 / 1024, 2) . " MB\n";
echo "空きメモリ: " . number_format($memory['free_memory'] / 1024 / 1024, 2) . " MB\n";
echo "無駄になったメモリ: " . number_format($memory['wasted_memory'] / 1024 / 1024, 2) . " MB\n";
echo "現在の無駄率: " . number_format($memory['current_wasted_percentage'], 2) . "%\n";
?>
3. 統計情報(ヒット率など)
<?php
$status = opcache_get_status();
$stats = $status['opcache_statistics'];
echo "ヒット数: " . number_format($stats['hits']) . "\n";
echo "ミス数: " . number_format($stats['misses']) . "\n";
echo "ヒット率: " . number_format($stats['opcache_hit_rate'], 2) . "%\n";
echo "キャッシュされたスクリプト数: " . number_format($stats['num_cached_scripts']) . "\n";
echo "キーの最大数: " . number_format($stats['max_cached_keys']) . "\n";
?>
実践的な活用例
OPcacheの健康状態をチェックする関数
<?php
function checkOpcacheHealth() {
$status = opcache_get_status();
if ($status === false) {
return "OPcacheが利用できません";
}
$issues = [];
// ヒット率をチェック
$hitRate = $status['opcache_statistics']['opcache_hit_rate'];
if ($hitRate < 90) {
$issues[] = "ヒット率が低い: {$hitRate}%";
}
// メモリ無駄率をチェック
$wasteRate = $status['memory_usage']['current_wasted_percentage'];
if ($wasteRate > 5) {
$issues[] = "メモリの無駄率が高い: {$wasteRate}%";
}
// キャッシュフル状態をチェック
if ($status['cache_full']) {
$issues[] = "キャッシュが満杯です";
}
return empty($issues) ? "OPcacheは健康です" : "問題: " . implode(", ", $issues);
}
echo checkOpcacheHealth();
?>
簡易監視ダッシュボード
<?php
function displayOpcacheDashboard() {
$status = opcache_get_status();
if ($status === false) {
echo "<h2>OPcacheダッシュボード</h2>";
echo "<p style='color: red;'>OPcacheが利用できません</p>";
return;
}
$memory = $status['memory_usage'];
$stats = $status['opcache_statistics'];
echo "<h2>OPcacheダッシュボード</h2>";
echo "<h3>基本情報</h3>";
echo "<p>ヒット率: <strong>" . number_format($stats['opcache_hit_rate'], 2) . "%</strong></p>";
echo "<p>キャッシュされたスクリプト数: <strong>" . number_format($stats['num_cached_scripts']) . "</strong></p>";
echo "<h3>メモリ使用状況</h3>";
$totalMemory = $memory['used_memory'] + $memory['free_memory'];
$usagePercent = ($memory['used_memory'] / $totalMemory) * 100;
echo "<p>メモリ使用率: <strong>" . number_format($usagePercent, 2) . "%</strong></p>";
echo "<p>使用中: " . number_format($memory['used_memory'] / 1024 / 1024, 2) . " MB</p>";
echo "<p>空き: " . number_format($memory['free_memory'] / 1024 / 1024, 2) . " MB</p>";
echo "<p>無駄: " . number_format($memory['wasted_memory'] / 1024 / 1024, 2) . " MB (" .
number_format($memory['current_wasted_percentage'], 2) . "%)</p>";
// 色分けによる視覚的表示
$hitRateColor = $stats['opcache_hit_rate'] >= 95 ? 'green' :
($stats['opcache_hit_rate'] >= 85 ? 'orange' : 'red');
echo "<p>ステータス: <span style='color: {$hitRateColor}; font-weight: bold;'>";
echo $stats['opcache_hit_rate'] >= 95 ? '優秀' :
($stats['opcache_hit_rate'] >= 85 ? '普通' : '要改善');
echo "</span></p>";
}
// HTMLヘッダー付きで表示
echo "<!DOCTYPE html><html><head><meta charset='UTF-8'><title>OPcache Dashboard</title></head><body>";
displayOpcacheDashboard();
echo "</body></html>";
?>
キャッシュされたスクリプトの詳細を確認
<?php
// include_scripts パラメータを使用
$status = opcache_get_status(true);
if (isset($status['scripts'])) {
echo "<h3>キャッシュされたスクリプト一覧</h3>";
foreach ($status['scripts'] as $script => $info) {
echo "<p><strong>{$script}</strong></p>";
echo "<ul>";
echo "<li>ヒット数: " . $info['hits'] . "</li>";
echo "<li>メモリ消費: " . number_format($info['memory_consumption']) . " bytes</li>";
echo "<li>最終使用: " . date('Y-m-d H:i:s', $info['last_used_timestamp']) . "</li>";
echo "</ul>";
}
}
?>
パフォーマンス最適化のヒント
1. ヒット率が低い場合の対策
<?php
$status = opcache_get_status();
$hitRate = $status['opcache_statistics']['opcache_hit_rate'];
if ($hitRate < 90) {
echo "ヒット率改善のための提案:\n";
echo "- opcache.memory_consumption の値を増やす\n";
echo "- opcache.max_accelerated_files の値を増やす\n";
echo "- 不要なファイルのincludeを減らす\n";
}
?>
2. メモリ使用量の監視
<?php
function monitorOpcacheMemory() {
$status = opcache_get_status();
$memory = $status['memory_usage'];
$totalMemory = $memory['used_memory'] + $memory['free_memory'] + $memory['wasted_memory'];
$usagePercent = ($memory['used_memory'] / $totalMemory) * 100;
if ($usagePercent > 90) {
// アラート処理
error_log("OPcache memory usage is high: " . number_format($usagePercent, 2) . "%");
}
if ($memory['current_wasted_percentage'] > 10) {
// 再起動を検討
error_log("OPcache wasted memory is high: " . $memory['current_wasted_percentage'] . "%");
}
}
?>
トラブルシューティング
よくある問題と解決方法
opcache_get_status()
が false を返す- OPcacheがインストールされていない
- php.ini で opcache が有効になっていない
- CLI環境でopcache.enable_cliがfalseになっている
- ヒット率が異常に低い
- ファイルが頻繁に更新されている
- opcache.validate_timestamps が有効で、開発環境である
- メモリ不足でキャッシュが頻繁にクリアされている
- メモリ使用量が多すぎる
- 不要なファイルがキャッシュされている
- opcache.memory_consumption の設定が適切でない
まとめ
opcache_get_status
関数は、PHPアプリケーションのパフォーマンス最適化において非常に重要な役割を果たします。定期的にOPcacheの状態を監視し、適切な設定調整を行うことで、Webアプリケーションの応答速度を大幅に改善することができます。
特に本番環境では、この関数を使用した監視スクリプトを定期実行し、パフォーマンスの問題を早期に発見することをお勧めします。
関連記事:
- PHPのOPcache設定最適化ガイド
- Webアプリケーション高速化テクニック
- PHP performance monitoring best practices