You can use max_statement_time
to prevent the query from taking more than 3 seconds to execute, for example:
MariaDB 10.1:
SET STATEMENT MAX_STATEMENT_TIME = 3000 FOR SELECT * FROM tabela WHERE vaiDemorar = 1
MySQL 5.7.7 +: (via Optimize Hint
)
SELECT /*+ MAX_EXECUTION_TIME(3000) */ * FROM tabela WHERE vaiDemorar = 1
All cases:
SET SESSION MAX_EXECUTION_TIME = 3000;
SELECT * FROM tabela WHERE vaiDemorar = 1;
This affects every SELECT you make in the same session.
This will interrupt the query execution by dropping an "error occurred" if it takes more than 3 seconds to complete.
If your intent is to only identify possible slow and slow querys you can set a slow_query_log_file
and then enable slow_query_log
, so you can discover the problems in the queries.
If you really want to find the query execution time in PHP, then use profiling
, as follows:
// Habilite o profiling
$mysqli->query('SET PROFILING = 1');
// Sua query, neste caso um exemplo de 2 + 2:
$matematica = $mysqli->query('SELECT 2 + 2');
list($resultado) = $matematica->fetch_row();
// Obtêm duração da query:
$profiling = $mysqli->query('SHOW profiles');
list(,$tempo_execução) = $profiling->fetch_row();
// Mostra o resultado:
echo $tempo_execução;
echo '<br>';
echo $resultado;
Result:
0.00009929
4
Therefore, it would be enough to use:
if($tempo_execução > 3){
echo 'Demorou mais de três segundos';
}