in reply to using grep on a directory to list files for a single date
Just for fun, I wanted to measure the speed difference of greping and just using while.
So I created, in a test directory, lots of small files :
$dir = "test"; mkdir $dir or die "Unable to create dir : $!" if not ( -d "$dir"); chdir $dir; foreach ( 'aaa' .. 'zzz' ) { open F, "> $_"; my $data = chr(97 + int rand 10); print F $data; close F; }
Then I tried to list each file of this directory, and compare :</o>
use Benchmark qw/cmpthese/; $dir = "test"; opendir DIR, "< $dir"; cmpthese(1000, { 'grep' => sub { opendir DIR, "$dir" or die "Unable to open dir : $!\n"; @list=grep(!/^(\.+?)$/,readdir(DIR)); closedir DIR; }, 'while' => sub { opendir DIR, "$dir" or die "Unable to open dir : $!\n"; while (readdir(DIR)) { push @list, $_ unless /^(\.+?)$/; closedir DIR; } } });
As expected, the difference is huge :
D:\Perl\bin>perl test2.pl Rate grep while grep 6.51/s -- -100% while 2667/s 40833% -- D:\Perl\bin>
Using grep, perl interprets readdir in list context, and builds and return the whole list of files of the directory, that is huge.
When using while, perl returnes file names each by each, which is much cheaper in memory.
So, in your case : use while.
For information, I was using Windows XP SP1 and ActivePerl 5.8.4 on a NTFS file system.
HTH
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: using grep on a directory to list files for a single date
by markkneen (Acolyte) on Dec 01, 2004 at 14:53 UTC | |
by ikegami (Patriarch) on Dec 01, 2004 at 15:07 UTC | |
by ikegami (Patriarch) on Dec 01, 2004 at 16:25 UTC | |
by revdiablo (Prior) on Dec 01, 2004 at 18:25 UTC |