2

我想测量在 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;
}
4

3 回答 3

6

我将Benchmark核心 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;
    #...
}
于 2013-08-07T06:18:37.517 回答
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

于 2013-08-07T05:52:47.200 回答
0

如果您有一个更复杂的案例,并且想要分析您的 perl 脚本以查看使用时间最多的地方,您应该查看很棒的 Devel::NYTProf(例如参见http://augustinalareina.wordpress.com/2011/02 /05/getting-started-with-develnytprof/)。它会告诉你一个函数被调用的频率、平均调用的时间以及所有这些都需要多长时间等等......

这样你就可以真正看到你在哪里浪费了时间,并且可以专注于优化实际上可能有意义的部分,并衡量你所做的任何改进(甚至相反)。

希望这对你有帮助,克里斯蒂安

于 2013-08-07T08:39:07.663 回答