How can I show the query time in Perl, DBI?

拜拜、爱过 提交于 2019-11-30 03:28:28

问题


I use Perl and DBI to manage my MySQL tables, querys, etc. How can I show the running time of a query?

If I do a SELECT in the console, the result will be like this:

+-----+-------------+
| id  | name        |
+-----+--------------
|   1 | Jack        |
|   2 | Joe         |
|   3 | Mary        |
+-----+-------------+
3 rows in set (0.17 sec)

I need to show 0.17 sec. There is any way in DBI to show the running time in Perl, something like this?

my $dbh = $db->prepare("SELECT id, name FROM names ORDER BY id;");
$dbh->execute;
print $dbh->runnin_time; # ???

回答1:


I can't find anything in DBI. I think that there is nothing already implemented out of the box, though could be interesting information.

The other way to do this would be to get the time before and after the execution and then make a simple difference. You can do it from within your Perl script simply getting the time stamp before the query execution, and after, then subtract the two to find the execution time.

my $start = DateTime->now;
my $dbh = $db->prepare("SELECT id, name FROM names ORDER BY id;");
$dbh->execute;
my $end = DateTime->now;


my $elapsedtime = ($end->subtract_datetime($start))->seconds;
print "Execution time(seconds) : $elapsedtime \n";



回答2:


DBI#Profile, DBI::Profile, DBI::ProfileData, DBI::ProfileDumper, dbiprof




回答3:


You take a timestamp before you run the query, and a timestamp after. The difference is your query execution time. For obtaining high-resolution timestamps, see Time::HiRes




回答4:


Reading @daxim's links to documentation, there is a simple way to achieve this by running your script with DBI_PROFILE=2 which is from DBI::Profile

Example output:

DBI::Profile: 53.203692s 50.67% (6725 calls) script.pl @ 2016-01-21 11:51:49
'INSERT INTO FOO ("BAR") VALUES (?)' =>
    0.057596s / 2 = 0.028798s avg (first 0.051621s, min 0.005975s, max 0.051621s)
'INSERT INTO BAZ ("QUX") VALUES (?)' =>
    0.367184s / 44 = 0.008345s avg (first 0.039410s, min 0.002445s, max 0.039410s)


来源:https://stackoverflow.com/questions/10799114/how-can-i-show-the-query-time-in-perl-dbi

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