r/PythonLearning • • 1d 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")
2 Upvotes

6 comments sorted by

3

u/p1geondove 1d ago

little messy, but should not be too slow, what are your times and how many files are deleted? i think the major bottleneck is the Path.stat() call, which you cant really do anything against. If your drive isnt overloaded you should easily get 10k files a second.

You are recasting from Path -> Path at the Path.is_dir() check.
You can add some early returns and remove some unnecessary checks
Did you time this with the prints? printing can take some time here aswell

Im still unsure on what exactly this does. Should it remove .pyc files from the project directory the file lives in, ergo its own project? Or should it be more universal and remove from other projects aswell? does the function live in the main file with the entry point or in another module?

i did rewrite it a little bit tho, but again your solution shouldnt be slow. it should delete all files withing a fraction of
a second

def stale_pyc_del_p1geon_1(path:str|Path):
    start = time.perf_counter()
    # is .resolve() really needed? afaik only useful for symlink which in this context shouldnt be (or you have some really weird structure)
    # shouldnt cost all too much anyway
    path = Path(path).resolve()

    if path.is_dir():
        # this would mean all files get deleted right?
        # cutoff = float('+inf')

        # do that directly and return early so you dont need to check for time for every file
        for f in (path / "__pycache__").glob("*.pyc"):
            f.unlink()
        return

    cur_file = Path(__file__)
    cutoff = max(path.stat().st_mtime, cur_file.stat().st_mtime)
    pycache_dir = path.parent / "__pycache__"

    if pycache_dir.is_dir():
        # there was a 'if path is None' check in here, but you also did Path(path) and Path(None) errors, so useless check?
        # filter or if check doesnt matter, i like filter, they look fancy (and 1 less indentation) :D
        for pyc_file in filter(lambda p:p.stat().st_mtime < cutoff, pycache_dir.glob("*.pyc")):
            pyc_file.unlink()

    stop = time.perf_counter()
    print(f"{path.name} - took {(stop-start)*1000:.3f}ms")


def stale_pyc_del_p1geon_2():
    """ removes all .pyc files from this project older than this file """
    # empty means "." so just relative, but should do the trick, probably same as Path(__file__).parent if this method lives in your entrypoint
    project_dir = Path()
    cutoff = Path(__file__).stat().st_mtime
    # using rglob instead of glob here, so this removes .pyc files from the entire project dir instea of just __pycache__
    # pyc files should only be in __pycache__ but this way you dont have to check wether __pycache__ dir even exists
    for pyc_file in filter(lambda p:p.stat().st_mtime < cutoff, project_dir.rglob("*.pyc")):
        pyc_file.unlink()

    # exactly the same as above
    # for pyc_file in project_dir.rglob("*.pyc"):
    #     if pyc_file.stat().st_mtime < cutoff:
    #         pyc_file.unlink()

1

u/RomfordNavy 10h ago

u/p1geondove very interesting improvements, thanks. I didn't even know that `rglob()` existed, so learnt something new.

However time is still around 130ms so I am currently working on doing it using `os.path` instead to see if that works out any faster.

0

u/Careful_Exercise_956 21h ago

Probably a time based thing

2

u/atarivcs 1d ago

If you're on linux, this is much easier done with a find command piped to xargs rm

find /some/path -type f -name "*.pyc" ! -newer timestamp_file | xargs rm

Where timestamp_file is a file with the desired modification timestamp cutoff date.

As a test, you can run just the find command without piping to xargs rm, to see the list of files it would remove.

1

u/RomfordNavy 10h ago

Needs to be able to run on both Windows and Linux.

4

u/sausix 1d ago

"find" has own action arguments like -delete.