http://qs321.pair.com?node_id=884080


in reply to Re: Get useful info about a directory tree
in thread Get useful info about a directory tree

Thanks for asking... Yes, I'd be grateful if someone could check my work on this:
#!/usr/bin/perl use strict; use Benchmark; use File::Find; $|++; my $Usage = "$0 some/path\n"; die $Usage unless @ARGV and -d $ARGV[0]; timethese( 30, { "\n Shell find pipe" => \&try_pipe, "\n _ Opendir recursion" => \&try_opendir, "\n __ File::Find module" => \&try_filefind, }); print "\n"; sub try_pipe { open( my $find, '-|', 'find', $ARGV[0], '-type', 'f' ); open( my $conf, '>', '/tmp/bm-conf.sh-find' ); my $counter; while (<$find>) { print $conf $_; $counter++; } print " $counter\r"; } sub try_opendir { open( my $conf, '>', '/tmp/bm-conf.opendir' ); my $counter = path_recurse( $ARGV[0], $conf ); print " $counter\r"; } sub path_recurse { my ( $path, $conf ) = @_; my $nfiles; opendir( my $dir, $path ) or return; while ( my $file = readdir( $dir )) { next if ( $file =~ /^\.{1,2}$/ or -l "$path/$file" ); if ( -f _ ) { print $conf "$path/$file\n"; $nfiles++; } elsif ( -d _ ) { $nfiles += path_recurse( "$path/$file", $conf ); } } return $nfiles; } sub try_filefind { my $counter; open( my $conf, '>', '/tmp/bm-conf.filefind' ); find( sub { if ( ! -l and -f _ ) { $counter++; print $conf "$File: +:Find::name\n" } }, $ARGV[0] ); print " $counter\r"; }
On a "mature" darwin laptop (2.16 GHz macbook, osx 10.6.6, perl 5.10.0, File::Find 1.12), with a tree containing 800 or so subdirectories at various depths, I get output like this (29485 is the count of data files):
Benchmark: timing 30 iterations of Shell find pipe, _ Opendir recursion, __ File::Find module... 29485 Shell find pipe: 7 wallclock secs ( 0.56 usr 0.40 sys + 1.03 cusr 3.87 csys = 5.8 +6 CPU) @ 5.12/s (n=30) 29485 _ Opendir recursion: 12 wallclock secs ( 3.79 usr + 5.63 sys = 9.42 CPU) @ 3.18/s (n=30 +) 29485 __ File::Find module: 20 wallclock secs ( 8.17 usr + 7.32 sys = 15.49 CPU) @ 1.94/s (n=30 +)
If you remove the parts about writing file names to temp files, the times all go down, but the relative proportions stay about the same. (I was writing temp files just to be sure I got the same output with each method. It took a few tries to handle the symbolic links consistently.)

I presume File::Find has a noticeable amount of overhead relative to a minimal recursion of opendir/readdir, but I haven't looked at the source code to check on that.