简体   繁体   English

Perl自定义运行时格式

[英]Perl custom run time format

I have an issue and this is rather my last resort before I give up, Im rather a noob with Perl and I've about reached the end of the internet searching for a solution. 我有一个问题,这是我放弃之前的最后一招,我是Perl的一个菜鸟,我已经到了互联网的终点寻找解决方案。

***I do not have permission to install anything so it must be native to Perl5 ***我没有权限安装任何东西,所以它必须是Perl5的原生

I have a script and I need to calculate the total runtime of the script, and output the result in 00.00 "minutes.seconds" stored in a variable. 我有一个脚本,我需要计算脚本的总运行时间,并输出存储在变量中的00.00“minutes.seconds”结果。

Here's a failed attempt: 这是一次失败的尝试:

#!/usr/bin/perl
use Time::Piece;
use POSIX qw(strftime);

my $start = localtime->strftime($unixtime);
sleep(10);
my $end = localtime->strftime($unixtime);
my $diff = $end - $start;
my $runtime = printf("%M.%S", $diff);
print $runtime;

I definitely have played with this a bit and was able to get "10" seconds as a result, however that is not the proper format. 我肯定已经玩过这一点了,因此能够得到“10”秒,但这不是正确的格式。 If the script ran for say 10 seconds, the output should be "00.10". 如果脚本运行了10秒,则输出应为“00.10”。

If the script ran for say 1 minute and 55 seconds the output should be "01.55". 如果脚本运行1分55秒,则输出应为“01.55”。

Is there any way this can be done? 有什么办法可以做到吗? I searched on this and found 1 article however not even close... REF: perl different time format output 我搜索了这个,发现了1篇文章但是没有关闭... REF: perl不同的时间格式输出

No need for Time::Piece! 不需要Time :: Piece!

my $start = time;
sleep(10);
my $end = time;
my $diff = $end - $start;
my $runtime = sprintf '%d:%02d', int($diff / 60), $diff % 60;
print "$runtime\n";

This should do the trick: 这应该做的伎俩:

#!/usr/bin/perl
use Time::Piece;

my $start = localtime;
sleep(10);
my $end = localtime;
my $diff = $end - $start;
my $minutes = int $diff->minutes;
my $seconds = $diff->seconds % 60;
my $output = sprintf '%02d.%02d', $minutes, $seconds;
print "$output\n";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM