如何获得perl函数所需的时间?

如何获得perl函数所需的时间?,perl,Perl,我想测量在perl中执行某些函数所需的时间。我使用了Time::HiRes,但时间不可读。如何才能轻松实现 代码是: use Time::HiRes qw (time); my $start = time; my_function_here (); my $time = time - $start; printf "Time needed for my_function_here is: $time sec\n"; sub my_function_here { my $null = 1

我想测量在perl中执行某些函数所需的时间。我使用了
Time::HiRes
,但时间不可读。如何才能轻松实现

代码是:

use Time::HiRes qw (time);
my $start = time;
my_function_here ();
my $time = time - $start;
printf "Time needed for my_function_here is: $time sec\n";

sub my_function_here {
    my $null = 1;
}

如果您指的是不可读的,如
7.86781311035156e-06
,这是因为函数太快,因此数字不像常规浮点那样简单。最好在函数之前使用一个循环,这样可以使数字更易于阅读

use Time::HiRes qw (time);
my $start = time;
foreach ( 1 ... 1000000 ){
    my_function_here ();
}
my $time = time - $start;
print "Time needed for my_function_here is: $time sec\n";

sub my_function_here {
    my $null = 1;
}
您的代码有
printf
必须打印的地方
print

我使用核心Perl模块来完成这类任务:

use strict;
use warnings;
use Benchmark qw/:hireswallclock/;

my $td = timeit(1, 'my_function_here');

print "the code took: ",timestr($td),"\n";
#<-- the code took: 2.86102e-006 wallclock secs ( 0.00 usr +  0.00 sys =  0.00 CPU)

sub my_function_here {
    my $null = 1;
    #...
}
使用严格;
使用警告;
使用基准qw/:hireswallclock/;
my$td=timeit(1,'my_function_here');
打印“所用代码:”,timestr($td),“\n”;

# 如果您有一个更复杂的案例,并且希望分析perl脚本以查看在哪里使用了最多的时间,那么您应该查看awesome Devel::NYTProf(例如,请参阅)。它会告诉你函数被调用的频率,平均调用多长时间,以及总共花费了多少时间,等等

通过这种方式,您可以真正看到您在哪里浪费了时间,并且可以将精力集中在优化实际上有意义的部分,并且还可以衡量您在哪里做出的任何改进(甚至相反)

希望这对你有帮助,
Christian

我认为你应该详细说明“不可读”。也许你可以粘贴一段你试过的代码?《时代周刊》:HiRes manpage中有很多例子。那么我如何才能猜出数字
1000000
,这样它就不会超过1秒,也不会小于0.09秒?使用
printf
打印字符串将一直工作到字符串中包含
%
字符。添加得很好。但问题在于foreach循环。所以这个数字对人类来说更具意义。只需把你想在timeit的第一个参数上执行的次数放进去。在我的例子中,它是1,将它更改为1000000或任何你想要的