Caveman profiling with a side of “where were you at 9pm on the night in question?” As always, season to taste.

<?
$_profile_log = "/tmp/php-profile.log";

function _profile() {
    static $fh;
    if( !isset($fh) ) {
        global $_profile_log;
        if( !file_exists($_profile_log) ) {
            @touch( $_profile_log );
            @chmod( $_profile_log, 0664 );
        }
        $fh = @fopen( $_profile_log, "a" );
    }
    if( !$fh )
        return false;

    $stack = debug_backtrace();
    if( $stack[1] )
        $base = $stack[1];
    else
        $base = $stack[0];
    $buf = $base['file'].":".$base['line'].", ";
    if( $base['class'] )
        $buf .= $base['class'].$base['type'];
    $buf .= $base['function'];

    $buf = sprintf("[%s] %s\n",date("H:i:s"),$buf);
    return @fwrite( $fh, $buf );
}
?>


Sample use:

<?
require_once "profiler.php";

// setup
function func() {
    _profile();
}

class obj {
    function method() {
        _profile();
    }
    function other_method() {
        func();
    }
    function indirect_method() {
        $this->method();
    }
}

$obj = new obj();

// actual invocation cases
_profile();
func();
obj::method();
$obj->method();
$obj->other_method();
$obj->indirect_method();
?>

Output:

ammon@elzar:~$ cat /tmp/php-profile.log
[19:00:21] /home/ammon/test.php:20, _profile
[19:00:21] /home/ammon/test.php:21, func
[19:00:21] /home/ammon/test.php:22, obj::method
[19:00:21] /home/ammon/test.php:24, obj->method
[19:00:21] /home/ammon/test.php:13, func
[19:00:21] /home/ammon/test.php:16, obj->method

Leave a Reply