很慢的目录()

时间:2011-06-17 12:08:51

标签: file matlab dir

当有大量文件时,大约4000,dir()功能非常慢。我的猜测是它会以低效的方式创建一个结构并填充值。

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

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

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

4 个答案:

答案 0 :(得分: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函数的另一种替代方法是在MATLAB中直接使用Java的java.io.File

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

ans =

        5000

答案 1 :(得分: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);DataHash来自http://www.mathworks.com/matlabcentral/fileexchange/31272。我跳过dir返回的数组的前两个元素,因为它们对应...

答案 2 :(得分:1)

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

更新:

我检查了超过4000个文件的目录。 dirls都显示出类似的结果:大约0.34秒。我觉得哪个不错。 (MATLAB 2011a,Windows 7 64位)

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

答案 3 :(得分: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)))
相关问题