大数据os.path.getsize上的Python代码性能

时间:2017-11-14 11:21:31

标签: python python-3.x performance os.walk

以下是我按升序获取文件大小的代码。

def Create_Files_Structure(directoryname):
   for path, subdirs, files in os.walk(directoryname,followlinks=False):
        subdirs[:] = [d for d in subdirs if not d[0] == '.']
        try:
           files_list.extend([(os.path.join(path, file),os.path.getsize(os.path.join(path, file))) for file in files ])
        except Exception as e:
            print()
   files_list.sort(key=lambda s: s[1], reverse=True)
   for pair in files_list:
     print(pair)
   print(len(files_list))

start=time.time()
Create_Files_Structure("/home/<username>")
end=time.time()
print(end-start)

此代码正在运行,但如果目录的大小在TB或PB中,则性能会很慢。任何改进代码以获得更快结果的建议请。

2 个答案:

答案 0 :(得分:1)

  1. 要了解您可以获得多快,请尝试在目录上运行并计时du -k。对于完整列表,您可能不会比使用Python更快。
  2. 如果您正在使用Python&lt; 3.5,尝试升级或使用scandir以获得良好的性能提升。
  3. 如果你真的不需要整个文件列表,但可以使用最大的1000个文件:
  4. 避免保留列表并将heapq.nlargest与生成器一起使用

    def get_sizes(root):
      for path, dirs, files in os.walk(root):
        dirs[:] = [d for d in dirs if not d.startswith('.')]
        for file in files:
            full_path = os.path.join(path, file)
            try:
              # keeping the size first means no need for a key function
              # which can affect performance
              yield (os.path.getsize(full_path), full_path)
            except Exception:
              pass
    
    import heapq
    for (size, name) in heapq.nlargest(1000, get_sizes(r"c:\some\path")):
      print(name, size)
    

    编辑 - 在Windows上更快 - os.scandir产生的条目已经包含大小,有助于避免另一个系统调用。

    这意味着使用os.scandir并自行递归,而不是依赖os.walk而不会产生该信息。

    scandir PEP 471中有一个类似的工作示例get_tree_size()功能,可以轻松修改以产生名称和大小。可以使用entry.stat(follow_symlinks=False).st_size访问每个条目的大小。

答案 1 :(得分:0)

好问题试试这个:

import time, os

def create_files_structuredire_2(ctoryname):

    files_list = []
    counter = 0

    for dirpath, _, filenames in os.walk(ctoryname):

        for items in filenames:

            file_full_path = os.path.abspath(os.path.join(dirpath, items))
            get_size = os.path.getsize(file_full_path)
            files_list.append((file_full_path, get_size))
            counter += 1

    files_list.sort(key=lambda s: s[1], reverse=True)
    [print(f) for f in files_list]
    print(counter)


start = time.time()
create_files_structuredire_2("your_target_folder")
end = time.time()
print(end-start)

注意:您的时间是0.044736385345458984,我的时间是0.001501321792602539 !!!!!!

祝你好运......