<?php
/*
 * Yes its ugly, its dirty but it gets the job done
 * *** Insert the following code into the bottom of your view/page
 *<script>
 *    window.open('phpgrind.php?pid=<?php echo getmypid; ?>', 'Win1','width=400, height=400');
 *</script>
 *
 * Richard Thomas
 * richard@phpjack.com
 * You can see this working online at http://solardemo.phpjack.com
 */


if(isset($_REQUEST['pid'])) {
    
$pid = (int) $_REQUEST['pid'];
} else {
    exit();
}
$file 'cachegrind.out.'.$pid;
$version '';
$recorded '';
$target '';
$data = array();
$fh fopen('/tmp/'.$file'r');
while(!
feof($fh)) {
    
$line fgets($fh4096);
    if(
strpos($line':')) {
        
$results explode(':'$line);
        
$value trim($results[1]);
        switch( 
trim$results[0])) {
            case 
'version':
                
$version $value;
                continue;
            break;
            case 
'events':
                
$recorded $value;
                continue;
            break;
            case 
'cmd':
                
$target $value;
                continue;
            break;
        }
    }
    
$pos strpos($line'fl=');
    if((
$pos == 0) AND ($pos !== false)) {
        
$fl trim(substr($line3));
        continue;
    }
    
$pos strpos($line'fn=');
    if((
$pos == 0) AND ($pos !== false)) {
        
$fn trim(substr($line3));
        continue;
    }
    if(isset(
$fl) AND isset($fn)) {
        
$counts explode(' '$line);
        if((
sizeof($counts) == 2) AND is_numeric(trim($counts[0])) AND is_numeric(trim($counts[1]))) {
            @
$data[$fl.':'.$fn]['time'] += $counts[1];        
            @
$data[$fl.':'.$fn]['count'] += 1;        
            unset(
$fn);
            unset(
$fl);
        }
    }
#    echo $line;
}

echo 
'<table cellborder=1  border=1 style="collapse-border: yes"><tr><td colspan=2>';
echo 
"Profiled Target:  $target<BR>";
echo 
"Events Recorded:  $recorded<BR>";
echo 
"Version:          $version<BR></td></tr>";
arsort($data);
foreach(
$data as $key => $value) {
    echo 
"<tr><td>{$value['time']}</td><td> $key</td></tr>";
}
exit();
?>
</table>