Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!
I have a question where I am trying to time and to log how long in a directory with a large number of files would take to open each file. I am using localtime() but I get the same time for all the files it find.
my $time = localtime(); foreach my $allfilesfound (@dir_contents) { print "This file=$allfilesfound tooke $time to be open<br +>"; }


Thanks for the help!

Replies are listed 'Best First'.
Re: Timing Files in Directory
by tirwhan (Abbot) on Mar 13, 2006 at 16:03 UTC

    That's because localtime() is only called once (during the variable assignment), not every time you print out the variable. If you want the time to be taken in each loop iteration you either need to assign to the variable inside the loop:

    foreach my $allfilesfound (@dir_contents) { my $time = localtime(); print "This file=$allfilesfound took $time to open<br>"; }

    Or assign it an anonymous subroutine and call that in the loop.

    my $time = sub { localtime() }; foreach my $allfilesfound (@dir_contents) { print "This file=$allfilesfound took ".$time->()." to open<br>"; }

    BTW, I'm assuming that you do more inside the loop than your example code shows, because this code doesn't actually open the file at all. Also, check out Time::HiRes for more accurate timing.


    All dogma is stupid.
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Timing Files in Directory
by CountOrlok (Friar) on Mar 13, 2006 at 15:57 UTC
    Your code is incomplete. Where do you actually try to open a file? You may want to look into the Benchmark module with the hireswallclock option.
    -imran