Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

后端 未结 9 1022
礼貌的吻别
礼貌的吻别 2021-01-30 02:30

When writing Perl scripts I frequently find the need to obtain the current time represented as a string formatted as YYYY-mm-dd HH:MM:SS (say 2009-11-29 14:28

9条回答
  •  时光说笑
    2021-01-30 02:41

    I made a little test (Perl v5.20.1 under FreeBSD in VM) calling the following blocks 1.000.000 times each:

    A

    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
    my $now = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $year+1900, $mon+1, $mday, $hour, $min, $sec);
    

    B

    my $now = strftime('%Y%m%d%H%M%S',localtime);
    

    C

    my $now = Time::Piece::localtime->strftime('%Y%m%d%H%M%S');
    

    with the following results:

    A: 2 seconds

    B: 11 seconds

    C: 19 seconds

    This is of course not a thorough test or benchmark, but at least it is reproducable for me, so even though it is more complicated, I'd prefer the first method if generating a datetimestamp is required very often.

    Calling (eg. under FreeBSD 10.1)

    my $now = `date "+%Y%m%d%H%M%S" | tr -d "\n"`;
    

    might not be such a good idea because it is not OS-independent and takes quite some time.

    Best regards, Holger

提交回复
热议问题