[CakePHP] Benchmarkコンポーネント(パフォーマンスの計測)

■ app/controllers/components/benchmark.php

<?php
/**
 * BenchmarkComponent
 * for CakePHP 1.3.x 〜
 */
class BenchmarkComponent extends Object {
	var $id = null;
	var $start_time = 0;

	/**
	 * コンストラクタ
	 */
	function __construct() {
		$this->id = substr( md5(uniqid(rand(),true)) , 0, 8);
		$this->report('<==construct', true);
	}

	/**
	 * デストラクタ
	 */
	function __destruct() {
		$this->report('<==destruct');
	}

	/**
	 * 計測してログを出力
	 */
	function report($message = null, $reset = false) {
		if (defined('BENCHMARK_MODE') === false || BENCHMARK_MODE === false) {
			return;
		}
		if ($reset === true) {
			$this->start_time = $this->_getMicroTime();
		}

		$noww = $this->_getMicroTime() - $this->start_time;

		$str = sprintf("[%s] %01.5f : %s :", $this->id, $now, $message);
		$this->log($str, LOG_DEBUG);
	}

	/**
	 * マイクロタイムを取得
	 */
	function _getMicrotime() {
		if (phpversion < 5) {
			list($usec, $sec) = explode(" ", microtime());
			return ((float)$usec + (float)$sec);
		} else {
			return microtime(true);
		}
	}
}

■ app/config/bootstrap.php

//ログを出力する場合は true 、出力しない場合は false
define('BENCHMARK_MODE', true);

■ app/controllers/hoge_controller.php

class HogeController extends AppController {
	var $name = 'Hoge';
	var $uses = array('Foo');
	var $components = array('Benchmark');

	function index() {

		$this->Benchmark->report(__FILE__ . ':' . __LINE__);
		//例)$this->Benchmark->report('start index()');

		//処理
		//例)$this->Foo->find('all', $params);

		$this->Benchmark->report(__FILE__ . ':' . __LINE__);
		//例)$this->Benchmark->report('find Foo');
	}
}
こちらもあわせてどうぞ
  1. [CakePHP] 「複数バリデーションの切り替え」と「エラーメッセージの自動生成」ができるビヘイビア
  2. [CakePHP] Thumbnailヘルパー(サムネイル画像)
  3. [CakePHP] Formヘルパーの拡張
  4. [CakePHP] TinyMCEヘルパー(見たまま編集エディター)
  5. [CakePHP] Textヘルパーの拡張
HatenaGoogle BookmarksYahoo BookmarksFacebook

コメントする

*