|
This code tells you how to log how much time each page took for execution. This method can be used for performance testing. If you are using some cms, then it is easy to find statistics of all the pages since we need to give the below code in header and footer only.
Here is the structure of MySql table:
CREATE TABLE `log_pages` (
`date` datetime NOT NULL,
`scriptname` varchar(255) NOT NULL,
`time` double NOT NULL,
`useragent` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
At the beginning of your page add this:
>
< ? php
// added by praveen - for performance log
$starttime = microtime();
$startarray = explode(" ", $starttime);
$starttime = $startarray[1] + $startarray[0];
?>
At the end of your page add this:
< ? php
// Added by praveen for performance log
$endtime = microtime();
$endarray = explode(" ", $endtime);
$endtime = $endarray[1] + $endarray[0];
$totaltime = $endtime - $starttime;
$totaltime = round($totaltime,5);
if ($totaltime >= 0.3) { // Since database table will become bulky if your site is having much traffic
// $lnk = @mysql_connect("localhost", "blah", "blah"); // no need to use if already a link object available
// @mysql_select_db("clipser_db"); // no need to use if already a link object available
@mysql_query("INSERT INTO log_pages (date, scriptname, time, useragent) VALUES (NOW(), '".$_SERVER["PHP_SELF"]."?".$_SERVER["QUERY_STRING"]."',".$totaltime . ",'". $_SERVER["HTTP_USER_AGENT"] . "');");
// @mysql_close($lnk); // no need to use if already a link object available
}
?>
You can ofcourse videw the data without phpMyAdmin like tools with the below script:<br />
<html>
<head>
<style>
th {
font-size:10px;
}
</style>
</head>
<body>
<small>Filter - Descending Order by "exec. time" - with > 0.4</small><br />
<table border="1" cellpadding="1" cellspacing="1" style="font:normal 9px arial">
<tr><th>Date-Time</th><th>filename</th><th>Exec. Time</th><th>Agent</th></tr>
< ?php
// Added by praveen for performance log
$lnk = mysql_connect("localhost", "blah", "blah");
mysql_select_db("clipser_db");
$resperf = mysql_query("SELECT date, scriptname, ROUND(time,2) AS time, useragent FROM log_pages WHERE time > 0.4 ORDER BY time DESC");
while (($row = mysql_fetch_assoc($resperf)) != false) {
echo "<tr><td>" . $row["date"] . "</td><td>" . $row["scriptname"] . "</td><th>" . $row["time"] . "</th><td> " . $row["useragent"] . "</td></tr>";
}
mysql_close($lnk);
?>
</table>
</body>
</html>
|