2011-06-17 81 views
3

当文件很多时,4000左右,dir()函数很慢。我的猜测是它创建了一个结构并以低效的方式填充了值。很慢dir()

是否有任何快速而优雅的替代品使用dir()

更新:使用MATLAB R2011a在64位Windows 7中进行测试。

更新2:大约需要2秒钟才能完成。

+0

使用掩码仅列出您想要的文件dir * data * .m`,例如 – jonsca 2011-06-17 12:22:10

+0

@jonsca:我需要目录中的所有文件,所以我需要所有〜4000个文件名。 – nimcap 2011-06-17 12:29:27

回答

1

您可以试试LS。它只返回字符数组中的文件名。我没有测试它是否比DIR更快。

更新:

我检查了超过4000个文件的目录。 dirls都显示类似的结果:约0.34秒。我认为这并不坏。 (MATLAB 2011a,Windows 7 64位)

您的目录位于本地硬盘驱动器或网络上吗?可能对硬盘进行碎片整理将有所帮助?

8

您正在使用哪种CPU/OS?我只是一个目录,5000个文件试了一下我的机器上,它是相当快:

>> d=dir; 
>> tic; d=dir; toc; 
Elapsed time is 0.062197 seconds. 
>> tic; d=ls; toc; 
Elapsed time is 0.139762 seconds. 
>> tic; d=dir; toc; 
Elapsed time is 0.058590 seconds. 
>> tic; d=ls; toc; 
Elapsed time is 0.063663 seconds. 
>> length(d) 

ans = 

     5002 

的另一个选择MATLAB的LS和DIR功能是直接使用Java的java.io.File在MATLAB:

>> f0=java.io.File('.'); 
>> tic; x=f0.listFiles(); toc; 
Elapsed time is 0.006441 seconds. 
>> length(x) 

ans = 

     5000 
6

确认了Jason S对联网驱动器和包含363个文件的目录的建议。 Win7 64位Matlab 2011a。

foobar都会产生相同的文件名单元阵列(使用数据的MD5散列验证),但使用Java的bar需要的时间要少得多。如果我先生成bar,然后foo生成类似的结果,那么这不是网络缓存现象。

 
>> tic; foo=dir('U:\mydir'); foo={foo(3:end).name}; toc 
Elapsed time is 20.503934 seconds. 
>> tic;bar=cellf(@(f) char(f.toString()), java.io.File('U:\mydir').list())';toc 
Elapsed time is 0.833696 seconds. 
>> DataHash(foo) 
ans = 
84c7b70ee60ca162f5bc0a061e731446 
>> DataHash(bar) 
ans = 
84c7b70ee60ca162f5bc0a061e731446 

其中cellf = @(fun, arr) cellfun(fun, num2cell(arr), 'uniformoutput',0);DataHashhttp://www.mathworks.com/matlabcentral/fileexchange/31272。我跳过由dir返回的数组中前两个元素,因为它们对应于...

1

%实施例:列表文件和文件夹

Folder = 'C:\'; %can be a relative path 
jFile = java.io.File(Folder); %java file object 
Names_Only = cellstr(char(jFile.list)) %cellstr 
Full_Paths = arrayfun(@char,jFile.listFiles,'un',0) %cellstr 

%实施例:列表文件(跳到文件夹)

Folder = 'C:\'; 
jFile = java.io.File(Folder); %java file object 
jPaths = jFile.listFiles; %java.io.File objects 
jNames = jFile.list; %java.lang.String objects 
isFolder = arrayfun(@isDirectory,jPaths); %boolean 
File_Names_Only = cellstr(char(jNames(~isFolder))) %cellstr 

%实施例:简单的过滤器

Folder = 'C:\'; 
jFile = java.io.File(Folder); %java file object 
jNames = jFile.list; %java string objects 
Match = arrayfun(@(f)f.startsWith('page')&f.endsWith('.sys'),jNames); %boolean 
cellstr(char(jNames(Match))) %cellstr 

%实施例:列表所有分类方法

methods(handle(jPaths(1))) 
methods(handle(jNames(1)))