首頁  >  文章  >  後端開發  >  加快 `shutil.copytree` 速度!

加快 `shutil.copytree` 速度!

WBOY
WBOY原創
2024-08-28 18:32:06398瀏覽

Speed up `shutil.copytree` !

關於加速shutil.copytree的討論

寫在這裡

這是關於 的討論,請參閱:https://discuss.python.org/t/speed-up-shutil-copytree/62078。如果您有任何想法,請發送給我!

背景

shutil 是 Python 中一個非常有用的模組。你可以在github中找到它:https://github.com/python/cpython/blob/master/Lib/shutil.py

shutil.copytree 是將一個資料夾複製到另一個資料夾的函式。

在該函數中,呼叫_copytree函數進行複製。

_copytree 有什麼作用?

  1. 忽略指定的檔案/目錄。
  2. 建立目標目錄。
  3. 在處理符號連結時複製檔案或目錄。
  4. 收集並最終提出遇到的錯誤(例如權限問題)。
  5. 將來源目錄的元資料複製到目標目錄。

問題

_當檔案數量較多或檔案大小較大時,copytree速度不是很快。

在這裡測試:

import os
import shutil

os.mkdir('test')
os.mkdir('test/source')

def bench_mark(func, *args):
    import time
    start = time.time()
    func(*args)
    end = time.time()
    print(f'{func.__name__} takes {end - start} seconds')
    return end - start

# write in 3000 files
def write_in_5000_files():
    for i in range(5000):
        with open(f'test/source/{i}.txt', 'w') as f:
            f.write('Hello World' + os.urandom(24).hex())
            f.close()

bench_mark(write_in_5000_files)

def copy():
    shutil.copytree('test/source', 'test/destination')

bench_mark(copy)

結果是:

write_in_5000_files 需要 4.084963083267212 秒
複製需要 27.12768316268921 秒

我做了什麼

多執行緒

我使用多執行緒來加速複製過程。我將函式重新命名為_copytree_single_threaded,新增一個新函式_copytree_multithreaded。這是copytree_multithreaded:

def _copytree_multithreaded(src, dst, symlinks=False, ignore=None, copy_function=shutil.copy2,
                            ignore_dangling_symlinks=False, dirs_exist_ok=False, max_workers=4):
    """Recursively copy a directory tree using multiple threads."""
    sys.audit("shutil.copytree", src, dst)

    # get the entries to copy
    entries = list(os.scandir(src))

    # make the pool
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        # submit the tasks
        futures = [
            executor.submit(_copytree_single_threaded, entries=[entry], src=src, dst=dst,
                            symlinks=symlinks, ignore=ignore, copy_function=copy_function,
                            ignore_dangling_symlinks=ignore_dangling_symlinks,
                            dirs_exist_ok=dirs_exist_ok)
            for entry in entries
        ]

        # wait for the tasks
        for future in as_completed(futures):
            try:
                future.result()
            except Exception as e:
                print(f"Failed to copy: {e}")
                raise

我新增了一個判斷,選擇是否使用多執行緒。

if len(entries) >= 100 or sum(os.path.getsize(entry.path) for entry in entries) >= 100*1024*1024:
        # multithreaded version
        return _copytree_multithreaded(src, dst, symlinks=symlinks, ignore=ignore,
                                        copy_function=copy_function,
                                        ignore_dangling_symlinks=ignore_dangling_symlinks,
                                        dirs_exist_ok=dirs_exist_ok)

else:
    # single threaded version
    return _copytree_single_threaded(entries=entries, src=src, dst=dst,
                                        symlinks=symlinks, ignore=ignore,
                                        copy_function=copy_function,
                                        ignore_dangling_symlinks=ignore_dangling_symlinks,
                                        dirs_exist_ok=dirs_exist_ok)

測試

我在來源資料夾中寫入了 50000 個檔案。基準標記:

def bench_mark(func, *args):
    import time
    start = time.perf_counter()
    func(*args)
    end = time.perf_counter()
    print(f"{func.__name__} costs {end - start}s")

寫入:

import os
os.mkdir("Test")
os.mkdir("Test/source")

# write in 50000 files
def write_in_file():
    for i in range(50000):
         with open(f"Test/source/{i}.txt", 'w') as f:
             f.write(f"{i}")
             f.close()

兩個比較:

def copy1():
    import shutil
    shutil.copytree('test/source', 'test/destination1')

def copy2():
    import my_shutil
    my_shutil.copytree('test/source', 'test/destination2')

  • 「my_shutil」是我修改過的shutil版本。

副本 1 花費 173.04780609999943s
copy2 花費 155.81321870000102s

copy2 比 copy1 快很多。你可以跑很多次。

優點和缺點

使用多執行緒可以加快複製過程。但會增加記憶體佔用。但我們不需要在程式碼中重寫多線程。

非同步

感謝「巴瑞·史考特」。我會聽從他/她的建議:

透過使用非同步 I/O,您可能會以更少的開銷獲得相同的改進。

我寫了這些程式碼:

import os
import shutil
import asyncio
from concurrent.futures import ThreadPoolExecutor
import time


# create directory
def create_target_directory(dst):
    os.makedirs(dst, exist_ok=True)

# copy 1 file
async def copy_file_async(src, dst):
    loop = asyncio.get_event_loop()
    await loop.run_in_executor(None, shutil.copy2, src, dst)

# copy directory
async def copy_directory_async(src, dst, symlinks=False, ignore=None, dirs_exist_ok=False):
    entries = os.scandir(src)
    create_target_directory(dst)

    tasks = []
    for entry in entries:
        src_path = entry.path
        dst_path = os.path.join(dst, entry.name)

        if entry.is_dir(follow_symlinks=not symlinks):
            tasks.append(copy_directory_async(src_path, dst_path, symlinks, ignore, dirs_exist_ok))
        else:
            tasks.append(copy_file_async(src_path, dst_path))

    await asyncio.gather(*tasks)
# choose copy method
def choose_copy_method(entries, src, dst, **kwargs):
    if len(entries) >= 100 or sum(os.path.getsize(entry.path) for entry in entries) >= 100 * 1024 * 1024:
        # async version
        asyncio.run(copy_directory_async(src, dst, **kwargs))
    else:
        # single thread version
        shutil.copytree(src, dst, **kwargs)
# test function
def bench_mark(func, *args):
    start = time.perf_counter()
    func(*args)
    end = time.perf_counter()
    print(f"{func.__name__} costs {end - start:.2f}s")

# write in 50000 files
def write_in_50000_files():
    for i in range(50000):
        with open(f"Test/source/{i}.txt", 'w') as f:
            f.write(f"{i}")

def main():
    os.makedirs('Test/source', exist_ok=True)
    write_in_50000_files()

    # 单线程复制
    def copy1():
        shutil.copytree('Test/source', 'Test/destination1')

    def copy2():
        shutil.copytree('Test/source', 'Test/destination2')

    # async
    def copy3():
        entries = list(os.scandir('Test/source'))
        choose_copy_method(entries, 'Test/source', 'Test/destination3')

    bench_mark(copy1)
    bench_mark(copy2)
    bench_mark(copy3)

    shutil.rmtree('Test')

if __name__ == "__main__":
    main()

輸出:

副本 1 花費 187.21 秒
copy2 花費 244.33s
copy3 花費 111.27 秒


可以看到非同步版本比單執行緒版本更快。但單線程版本比多線程版本更快。 (可能是我的測試環境不太好,你可以嘗試一下,把你的結果回覆給我)

謝謝巴瑞·史考特!

優點和缺點

非同步是一個不錯的選擇。但沒有一個解決方案是完美的。如果您發現任何問題,可以回覆我。

結尾

這是我第一次在 python.org 寫討論。如果有任何問題,請告訴我。謝謝。

我的Github:https://github.com/mengqinyuan
我的開發者:https://dev.to/mengqinyuan

以上是加快 `shutil.copytree` 速度!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn