在 Laravel 中测试查询执行时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41745339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:09:58  来源:igfitidea点击:

Test query execution time in laravel

phpmysqllaravelphpunit

提问by changer

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

如何在laravel/phpunit 中测试执行查询需要多长时间?

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

有没有可能使它不依赖于其他东西?

回答by Alexey Mezenin

The oldest way is the best one:

最古老的方法是最好的:

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

回答by j3py

Since Laravel 5.2 listenhas changed to only except one argument:

由于 Laravel 5.2listen已更改为只有一个参数除外:

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

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

文档:https: //laravel.com/docs/5.2/database

回答by Samir Mammadhasanov

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

你可以ddd($someVar)从 Laravel 6.x 开始使用helper。

There is Queriestab which describes each query executed until ddd()

有一个Queries选项卡描述了执行的每个查询,直到ddd()

回答by Gayan

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

您可以listen像这样执行查询并将结果记录在storage/logs/laravel.log.

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

You could just use $timeonly, but I logged $sql, $bindings, $timefor the completion.

你只能使用$time,但我登录$sql, $bindings, $time完成。

You could put this inside your AppServiceProvider.

你可以把它放在你的AppServiceProvider.

UPDATE:

更新:

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

在 Laravel 版本 > 5.5 中,此方法在文档中记录为侦听查询事件;)