r/pythonhelp • u/RomfordNavy • 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")1
1
u/Individual-Flow9158 11h 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.
•
u/AutoModerator 1d 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.