r/pythonhelp • • 8d ago

pathlib.Path quite slow

pathlib.Path appears to run much slower than I expected. The following function deletes .pyc files older than that of the filename passed in as a parameter.

Is there a faster alternative way of doing this?

import time
from pathlib import Path

def stale_pyc_del(path: str) -> None:
    spd_start = time.perf_counter()
    cur_import = Path(path).resolve()
    if Path.is_dir(cur_import):
        cutoff_time = float('+inf')
        pycache_dir = cur_import / "__pycache__"
    else: # file not directory
        cur_file = Path(__file__).resolve()
        cutoff_time = max(cur_file.stat().st_mtime, cur_import.stat().st_mtime)
        pycache_dir = cur_import.parent / "__pycache__"
    if pycache_dir.is_dir():
        for pyc_file in pycache_dir.glob("*.pyc"):
            # print(f"{pyc_file=}, {pyc_file.stat().st_mtime=}, {cutoff_time}")
            if path is None or pyc_file.stat().st_mtime < cutoff_time:
                print(f"deleting: {pyc_file=}")
                pyc_file.unlink()
    spd_end = time.perf_counter()
    print("stale_pyc_del:", os.path.basename(path), "-", f"{((spd_end - spd_start) * 1000):.3f}", "ms")
3 Upvotes

16 comments sorted by

View all comments

Show parent comment

1

u/RomfordNavy 3d ago

The 10-second guard isn't relevant to the timings as is getting run only once anyway. You suggest testing with caching disabled, any idea how to do that from code?

2

u/DickBrainTime 2d ago

You're right: a single call makes the 10-second guard irrelevant. I meant the OS filesystem cache; Python can't portably turn that off. Run each version on identical copies of the files (since they delete files), alternate the order, and time path resolution separately from scanning. The changed cutoff and traversal logic still make 130 ms vs 10 ms an uneven comparison.

1

u/RomfordNavy 1d ago

Have tried removing cutoff and testing that against pathlib version with same traversal logic as this and time difference is still 130ms vs 10ms.

2

u/DickBrainTime 1d ago

That narrows it down. Your original pathlib version calls Path(path).resolve() (and resolves __file__), while the os.path version doesn't. Try timing resolution separately, then compare Path(path) for an already-absolute path; if the gap remains, time is_dir, enumeration and stat one stage at a time.

1

u/RomfordNavy 1d ago

Over half of the time is in `Path(path).resolve()`

2

u/DickBrainTime 1d ago

Nice, that explains a big chunk. For this cleanup, try Path(path) without .resolve() (and skip resolving __file__ too); is_dir(), stat() and glob() can work with relative paths. If you need canonical or symlink-resolved paths, keep it; otherwise compare the remaining scan time with those calls removed.

1

u/RomfordNavy 1d ago

Having now removed the `.resolve()` pathlib is a bit faster but now `glob()` seems to be the bottleneck. With no files in the directory to delete the pathlib version is 60ms as opposed to the `os.path` version which is 2ms.

1

u/DickBrainTime 18h ago

60ms on an empty folder sounds worth separating first-call overhead from repeated work. Try warming up glob once, then time several runs on that same empty folder against os.scandir with the same .pyc filter. If the steady-state gap stays that big, os.scandir is reasonable for this hot path.