Created
January 20, 2012 19:22
-
-
Save bahulneel/1649103 to your computer and use it in GitHub Desktop.
Counts queries and the time they spend executing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function removeVars($sql) | |
{ | |
$sql = preg_replace('/(\b)\d+(\b)/', '\1?\2', $sql); | |
$sql = str_replace('?, ', '', $sql); | |
$sql = str_replace("\t", ' ', $sql); | |
return $sql; | |
} | |
list (, $host, $dbName, $user, $pass) = $_SERVER['argv']; | |
$db = new PDO( | |
'mysql:host=' . $host . ';dbname=' . $dbName, | |
$user, | |
$pass | |
); | |
$procs = array(); | |
$queries = array(); | |
$start = time(); | |
$complete = array(); | |
while (time() - $start < 6) { | |
$stmt = $db->query('show full processlist'); | |
$procList = $stmt->fetchAll(PDO::FETCH_ASSOC); | |
$time = microtime(true); | |
foreach ($procs as &$proc) { | |
$proc['complete'] = true; | |
} | |
foreach ($procList as $proc) { | |
$id = $proc['Id']; | |
if (isset($procs[$id]) && $procs[$id]['Info'] !== $proc['Info']) { | |
$procs[$id]['currentTime'] = $time; | |
$complete[] = $procs[$id]; | |
unset($procs[$id]); | |
} | |
if (!isset($procs[$id])) { | |
$procs[$id] = $proc; | |
$procs[$id]['startTime'] = $time; | |
} | |
$procs[$id]['complete'] = false; | |
$procs[$id]['currentTime'] = $time; | |
} | |
foreach ($procs as $id => $proc) { | |
if ($proc['complete']) { | |
$complete[] = $proc; | |
unset($procs[$id]); | |
} | |
} | |
} | |
foreach ($complete as $proc) { | |
$query = removeVars($proc['Info']); | |
$time = $proc['currentTime'] - $proc['startTime']; | |
$hash = md5($query); | |
if (!isset($queries[$hash])) { | |
$queries[$hash] = array( | |
'sql' => $query, | |
'count' => 0, | |
'time' => 0 | |
); | |
} | |
$queries[$hash]['count']++; | |
$queries[$hash]['time']+=$time; | |
$queries[$hash]['meanTime'] = $queries[$hash]['time'] / $queries[$hash]['count']; | |
} | |
$headerSent = false; | |
foreach ($queries as $query) { | |
if (!$headerSent) { | |
$headerSent = true; | |
echo implode("\t", array_keys($query)) . PHP_EOL; | |
} | |
echo implode("\t", $query) . PHP_EOL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment