我每晚都在处理一个大目录.它每晚累积大约100万个文件,其中一半是我需要根据内容移动到不同目录的.txt文件.
每个.txt文件都是以管道分隔的,只包含20条记录.记录6是包含确定将文件移动到哪个目录所需的信息的记录.
记录示例:
A|CHNL_ID|4
在这种情况下,文件将被移动到/ out / 4.
此脚本的处理速度为每小时80,000个文件.
有关如何加快速度的建议吗?
opendir(DIR,$dir) or die "$!\n"; while ( defined( my $txtFile = readdir DIR ) ) { next if( $txtFile !~ /.txt$/ ); $cnt++; local $/; open my $fh,'<',$txtFile or die $!,$/; my $data = <$fh>; my ($channel) = $data =~ /A\|CHNL_ID\|(\d+)/i; close($fh); move ($txtFile,"$outDir/$channel") or die $!,$/; } closedir(DIR);
解决方法
尝试类似的东西:
print localtime()."\n"; #to find where time is spent opendir(DIR,$dir) or die "$!\n"; my @txtFiles = map "$dir/$_",grep /\.txt$/,readdir DIR; closedir(DIR); print localtime()."\n"; my %fileGroup; for my $txtFile (@txtFiles){ # local $/ = "\n"; #\n or other record separator open my $fh,$txtFile or die $!; local $_ = join("",map {<$fh>} 1..6); #read 6 records,not whole file close($fh); push @{ $fileGroup{$1} },$txtFile if /A\|CHNL_ID\|(\d+)/i or die "No channel found in $_"; } for my $channel (sort keys %fileGroup){ moveGroup( @{ $fileGroup{$channel} },"$outDir/$channel" ); } print localtime()." finito\n"; sub moveGroup { my $dir=pop@_; print localtime()." <- start $dir\n"; move($_,$dir) for @_; #or something else if each move spawns sub process #rename($_,$dir) for @_; }
这将作业分成三个主要部分,您可以在每个部分计算时间以查找花费大部分时间的位置.