Computing MySQL Queries Per Second

I need an excuse to test out the code highlighting plugin I just installed here, so I’ll share how I display the “visits per second” in the Random Statistics box in the sidebar of this site. The visits per second being processed by W3Counter is computed by dividing the queries per second the database is handling by the number of queries run for each visit.

To obtain queries per second, I compare the number of queries MySQL has handled since its last restart to the number last time I checked and divide by the time difference. Here’s the basic code:

$last = split("-", file_get_contents('queries.txt'));
$timestamp_old = $last[0];
$queries_old = $last[1];

$row = mysql_fetch_assoc(mysql_query("show status like 'Questions'", $connection));
$queries_new = $row['Value'];
$timestamp_new = time();

$qps = round(($queries_new - $queries_old) / ($timestamp_new - $timestamp_old));

$fhandle = fopen('queries.txt', 'w');
fwrite($fhandle, $timestamp_new . "-" . $queries_new);
fclose($fhandle);

More from this category

  • http://www.webdigity.com/ Nick

    This snippet can cause a server crash if more than one processes run it simultaneously. You should use flock() with the file handle.

  • Pingback: us cellular text messaging