視圖中直接顯示
<!-- view 檔案中 -->
<div class="debug-info">
記憶體使用量: <?= $this->benchmark->memory_usage() ?>
</div>
<!-- 或使用偽變數(需啟用 parse_vars)-->
<div class="debug-info">
記憶體使用量: {memory_usage}
</div>
控制器中程式化取得
<?php
public function debugMemory() {
$this->load->library('benchmark');
// 取得格式化字串(如 "2.5 MB")
$usage = $this->benchmark->memory_usage();
// 取得原始位元組數(CodeIgniter 3)
$bytes = memory_get_usage(true); // true = 含系統分配
echo "Benchmark: $usage\n";
echo "Raw bytes: " . number_format($bytes) . " bytes\n";
echo "Raw MB: " . round($bytes / 1024 / 1024, 2) . " MB\n";
}
?>
Benchmark Library 完整方法
| 方法 | 說明 | 偽變數 |
elapsed_time([$point1, $point2]) | 執行時間(秒),可指定標記點 | {elapsed_time} |
memory_usage() | 記憶體使用量(格式化) | {memory_usage} |
mark($name) | 設定時間標記點 | - |
進階:標記點測量特定區段效能
<?php
public function profileQuery() {
$this->benchmark->mark('query_start');
// 執行複雜查詢
$results = $this->db->query('SELECT * FROM large_table JOIN ...')->result();
$this->benchmark->mark('query_end');
echo "查詢耗時: " . $this->benchmark->elapsed_time('query_start', 'query_end') . " 秒\n";
echo "記憶體: " . $this->benchmark->memory_usage() . "\n";
// 多標記點
$this->benchmark->mark('cache_start');
$this->cache->save('key', $data, 3600);
$this->benchmark->mark('cache_end');
echo "快取寫入: " . $this->benchmark->elapsed_time('cache_start', 'cache_end') . " 秒\n";
}
?>
PHP 原生記憶體函數對照
| 函數 | 說明 | 單位 |
memory_get_usage(true) | 目前腳本使用記憶體(含系統分配) | Bytes |
memory_get_usage(false) | 目前腳本使用記憶體(僅 PHP 內部) | Bytes |
memory_get_peak_usage(true) | 峰值記憶體使用量 | Bytes |
ini_get('memory_limit') | 記憶體限制設定 | String (如 "128M") |
記憶體優化建議
- 大量資料用
chunk() 或 cursor() 分批處理,避免一次載入
- 不用的大型變數及時
unset() 或設為 null
- 避免在迴圈中重複字串連接,用陣列
implode()
- 關閉不需要的資料庫欄位
select('id, name')
- 啟用 OPcache、調整
memory_limit 適當值
結語
CodeIgniter Benchmark Library 提供簡單的記憶體與時間監控。開發階段建議在頁面底部顯示 {memory_usage} | {elapsed_time},上線前關閉。搭配 PHP 原生函數可進行更精細的效能分析與優化。