r/pythonhelp • • 6d 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

12 comments sorted by

•

u/AutoModerator 6d ago

To give us the best chance to help you, please include any relevant code.
Note. Please do not submit images of your code. Instead, for shorter code you can use Reddit markdown (4 spaces or backticks, see this Formatting Guide). If you have formatting issues or want to post longer sections of code, please use Privatebin, GitHub or Compiler Explorer.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

2

u/atarivcs 6d ago

Why did you post this a second time

1

u/RomfordNavy 5d ago

Because the first post didn't work and just disappeared. However now appears to have reappeared.

2

u/Individual-Flow9158 6d ago

With PYTHONDONTWRITEBYTECODE set, or if Python is called with -B, it won't create .pyc files in the first place.

Regarding the question, the performance is going to be determined by the number of files in path or adjacent _pycache__ dirs, and the number of "sys calls" your code needs to make, with or without pathlib.

Prove me wrong by all means, but the excellent wrapper classes pathlib adds around oscalls, will have a negligible impact.

1

u/RomfordNavy 5d ago

Now rewritten using all `os.path` calls and what was 130ms with `pathlib` is now running sub 10ms.

1

u/Individual-Flow9158 3d ago

Perhaps you work at lightning speed, but that 120ms is negligible to most users, especially for a one off file processing script.

If those're honest, repeatable figures, then great work though.

2

u/RomfordNavy 3d ago

u/Individual-Flow9158 Here is the `os.path` version, you can test it yourself:

import time
import os

last_spd = None

def stale_pyc_del(path: str) -> None:
    global last_spd
    spd_start = time.perf_counter()
    if last_spd is None or time.time() > last_spd + 10:
        if os.path.isdir(path): # path = directory
            pycache_dir = path + "\__pycache__"
            cutoff_time = time.time()
        else: # path = file
            pycache_dir = os.path.dirname(path) + "\__pycache__"
            cutoff_time = os.path.getmtime(path)
        last_spd = time.time()
        if os.path.isdir(pycache_dir):
            for root, dirs, files in os.walk(pycache_dir):
                for file in files:
                    if file.endswith('.pyc') and (os.path.getmtime(filepath := root + "\\" + file)) < cutoff_time:
                        os.remove(filepath)

    spd_end = time.perf_counter()
    print("stale_pyc_del:", os.path.basename(path), "-", f"{((spd_end - spd_start) * 1000):.3f}", "ms")

Logic has changed a bit since the pathlib version but timings are still representative.

2

u/DickBrainTime 2d ago

Worth checking: your new version has a 10-second last_spd guard, so repeated calls skip the scan entirely; the pathlib version scans every time. It also switches from glob() to recursive os.walk() and changes cutoff logic. I'd benchmark the same work with caching disabled before treating 130 ms vs 10 ms as a pathlib comparison.

1

u/RomfordNavy 1d 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 1d 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 5h 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.

1

u/DickBrainTime 32m 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.