=================Perl:查找大於X分鐘數的文件的最快方法,將最早排序到最新?
1.查找文件不是幾分鐘的X數的
2.處理他們從最舊到最新
下面的代碼工作正常,但是該目錄包含3百萬個文件。因此我需要優化它以更快地找到文件。我不必擔心文件的內容只是名稱。
###########################
sub get_files_to_process{
###########################
# Declare arrays
my @xmlfiles;
my @qulfiedfiles;
# Declare a Dictionary
my %filedisc;
opendir(my $dh, $maindir) or die "opendir($maindir): $!";
# Read all the files
while (my $de = readdir($dh)) {
# get the Full path of the file
my $f = $maindir . $de;
# If File is there and has .xml Extension
if (-f $f && $f=~ /\.xml/){
# Put it in a XMLFILES Array
push (@xmlfiles, $f); }
}
closedir($dh);
# For every file in directory
for my $file (@xmlfiles) {
# Get stats about a file
my @stats = stat($file);
# If time stamp is older than minutes provided
if ($stats[9] <= ($now - (($minutesold * 60)))){
# Put the File and Time stamp in the dictionary
$filedisc{$file} = $stats[9];
}
}
# For every file in the dictionary sort based on the timestamp oldest files first
for my $x (sort {$filedisc{$a} <=> $filedisc{$b} or $a cmp $b } keys %filedisc) {
# Put the qualified files (Based on the age) in a list
push(@qulfiedfiles, $x);}
更新:到目前爲止,這似乎是做有前途的,更多的測試:
##########################
sub get_files_count{
##########################
my $cmd= "find $maindir -maxdepth 1 -name '*.xml' -mmin +$minutesold -printf \"%T+\t%p\\n\"| sort";
my @output = `$cmd`;
if (@output){
foreach my $line (@output){
chomp $line;
push (@files2process, (split '\t', $line)[ -1 ]);
}
}
}
我還沒有測試您的代碼與3_000_000條目的目錄。在我們開始討論優化代碼的方法之前,爲什麼不使用'Devel :: NYTProf'來確定代碼花費最多的時間? – DavidO 2014-08-27 21:21:04
一旦你有你的名單,你如何處理文件? – ThisSuitIsBlackNot 2014-08-27 21:35:42
@ThisSuitIsBlackNot,一旦我有文件列表,我根據文件的名稱將文件移動到適當的子目錄(並創建子目錄(如果尚未存在的話)),則此腳本將每隔cron用完5到10分鐘,Enterpise應用程序會生成大量的xml文件,這將會培養這些文件 – Grene 2014-08-28 01:30:01