我想使用gmtime()打印我的脚本在几分钟,几小时,几天和几周内完全在Perl中运行的时间。
例如
Compare
关于如何做的任何想法?
我可以使用分钟和小时来解决它,但我想要添加几天和几周
提前致谢
答案 0 :(得分:0)
使用time
代替gmtime
,您可以执行以下操作:
my $seconds = $finish - $start;
my $minutes = $seconds / 60;
my $hours = $minutes / 60;
my $days = $hours / 24;
my $weeks = $days / 7;
my $months = $weeks / (52 / 12);
my $years = $months / 12;
要获得相对大小(即2h2m而不是2h122m),您必须模拟下一个最高因子。它看起来像这样:
my $seconds = (my $raw_seconds = $finish - $start) % 60;
my $minutes = (my $raw_minutes = $raw_seconds / 60) % 60;
my $hours = (my $raw_hours = $raw_minutes / 60) % 24;
my $days = (my $raw_days = $raw_hours / 24) % 7;
my $weeks = (my $raw_weeks = $raw_days / 7) % (52 / 12);
my $months = (my $raw_months = $raw_weeks / (52 / 12)) % 12;
my $years = int(my $raw_years = $raw_months / 12);
如果您正在思考,"这看起来很重复,我们可以自动化吗?"
# Given total seconds, return relative seconds, minutes, hours, days, weeks,
# months, and years.
sub timeparts {
my @factors = (1, 60, 60, 24, 7, 52 / 12, 12);
my @rawparts = $_[0] // 0;
my @parts;
for (my $i = 0; $i < @factors; $i++) {
push @rawparts, $rawparts[-1] / $factors[$i];
push @parts, defined $factors[$i+1]
? $rawparts[-1] % $factors[$i+1]
: int $rawparts[-1];
}
return @parts;
}
幸运的是,有更简单的方法可以做到这一点。看看Time :: Piece,Time :: Seconds和Time :: Duration。