目录文件大小计算 - 如何使它更快吗? [英] Directory file size calculation - how to make it faster?

查看:160
本文介绍了目录文件大小计算 - 如何使它更快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C#,我发现一个目录的总大小。其中的逻辑是这样的:获取文件夹内的文件。综上所述的总大小。寻找是否有子目录。然后做递归搜索。

Using C#, I am finding the total size of a directory. The logic is this way : Get the files inside the folder. Sum up the total size. Find if there are sub directories. Then do a recursive search.

我尝试另一个方式做到这一点太:使用FSO( obj.GetFolder(路径).Size )。这里没有太大的区别在时间中这两种方法。

I tried one another way to do this too : Using FSO (obj.GetFolder(path).Size). There's not much of difference in time in both these approaches.

现在的问题是,我有文件数以万计的在一个特定的文件夹及其回吐像ATLEAST 2分钟找到该文件夹​​的大小。另外,如果我再次运行程序,它发生得很快(5秒)。我认为Windows是缓存文件大小。

Now the problem is, I have tens of thousands of files in a particular folder and its taking like atleast 2 minute to find the folder size. Also, if I run the program again, it happens very quickly (5 secs). I think the windows is caching the file sizes.

有没有什么办法可以降低当我运行该程序第一次所花费的时间?

Is there any way I can bring down the time taken when I run the program first time??

推荐答案

如果与它摆弄了一会儿,试图并行化,和令人惊讶 - 它加速了这里我的机器上(最多3次在四核),唐知道这是否是在所有情况下有效,但不妨一试...

If fiddled with it a while, trying to Parallelize it, and surprisingly - it speeded up here on my machine (up to 3 times on a quadcore), don't know if it is valid in all cases, but give it a try...

.NET4.0 code(或使用3.5 TaskParallelLibrary)

.NET4.0 Code (or use 3.5 with TaskParallelLibrary)

    private static long DirSize(string sourceDir, bool recurse)
    {
        long size = 0;
        string[] fileEntries = Directory.GetFiles(sourceDir);

        foreach (string fileName in fileEntries)
        {
            Interlocked.Add(ref size, (new FileInfo(fileName)).Length);
        }

        if (recurse)
        {
            string[] subdirEntries = Directory.GetDirectories(sourceDir);

            Parallel.For<long>(0, subdirEntries.Length, () => 0, (i, loop, subtotal) =>
            {
                if ((File.GetAttributes(subdirEntries[i]) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
                {
                    subtotal += DirSize(subdirEntries[i], true);
                    return subtotal;
                }
                return 0;
            },
                (x) => Interlocked.Add(ref size, x)
            );
        }
        return size;
    }

这篇关于目录文件大小计算 - 如何使它更快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆