我建議使用Time::Piece
。
它顯示性能提高6倍,如下面的基準所示。
如果您緩存可能的日期值,你可以得到所有百萬價值的幾乎瞬時的結果:
#!/usr/bin/perl -w
use strict;
use warnings;
use autodie;
use Benchmark;
use Data::Random qw(:all);
use Time::Piece;
use Time::Seconds;
my $randDate_Start = '1900-01-01';
my $randDate_End = '2010-12-31';
my $tp_start = Time::Piece->strptime("$randDate_Start 12:00:00", "%Y-%m-%d %T");
my $tp_end = Time::Piece->strptime("$randDate_End 12:00:00", "%Y-%m-%d %T");
my $tp_days = ($tp_end - $tp_start)->days;
my @tp_cached = map { ($tp_start + ONE_DAY * $_)->strftime('%Y-%m-%d') } (0 .. $tp_days);
# Compare Data Methods
timethese(
1_000_000,
{ 'Data::Random' => sub { rand_date(min => $randDate_Start, max => $randDate_End) },
'Time::Piece' => sub { ($tp_start + ONE_DAY * int rand $tp_days)->strftime('%Y-%m-%d') },
'Time::Piece (cached)' => sub { $tp_cached[ rand $tp_days ] },
}
);
輸出:
Benchmark: timing 1000000 iterations of Data::Random, Time::Piece, Time::Piece (cached)...
Data::Random: 61 wallclock secs (60.20 usr + 0.07 sys = 60.27 CPU) @ 16592.00/s (n=1000000)
Time::Piece: 10 wallclock secs (9.95 usr + 0.01 sys = 9.96 CPU) @ 100401.61/s (n=1000000)
Time::Piece (cached): 0 wallclock secs (0.08 usr + 0.00 sys = 0.08 CPU) @ 12500000.00/s (n=1000000)
(warning: too few iterations for a reliable count)
生成較少的樣本數據? – 2014-09-11 04:51:48
@ialarmedalien:汽車的速度並不取決於你駕駛的距離,Data :: Random的速度不受你所做的世代數量的影響。 – 2014-09-11 04:54:47
@RenéNffeffegger,但您的汽車行程所需的時間取決於行駛的距離。再一次,這不是目的地,這是重要的旅程。 – 2014-09-11 05:00:07