Test query execution time in laravel

雨燕双飞 提交于 2020-01-01 04:35:31

问题


How to test in laravel/phpunit how long query took to execute?

Is it possible so that it does not depend on something else?


回答1:


The oldest way is the best one:

$start = microtime(true);
// Execute the query
$time = microtime(true) - $start;



回答2:


Since Laravel 5.2 listen has changed to only except one argument:

\DB::listen(function ($query) {
     // $query->sql
     // $query->bindings
     // $query->time
});

Docs: https://laravel.com/docs/5.2/database




回答3:


You could listen to executing query like this and log the result in storage/logs/laravel.log.

\DB::listen(function ($sql, $bindings, $time) {
    \Log::info($sql, $bindings, $time);
});

You could just use $time only, but I logged $sql, $bindings, $time for the completion.

You could put this inside your AppServiceProvider.

UPDATE:

In Laravel version > 5.5 this approach is documented in the doc as listening for query events ;)




回答4:


You can use ddd($someVar) helper starting from Laravel 6.x.

There is Queries tab which describes each query executed until ddd()



来源:https://stackoverflow.com/questions/41745339/test-query-execution-time-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!