-
-
Notifications
You must be signed in to change notification settings - Fork 32k
GH-111429: Speed up pathlib.PurePath.[is_]relative_to()
#111431
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
GH-111429: Speed up pathlib.PurePath.[is_]relative_to()
#111431
Conversation
Thanks for the change! Overall LGTM. A small suggestion would be - would you mind doing a quick profiling of these 2 functions before/after the change please, just so that we can better understand the effect of the change? |
The improvement depends on the type of the argument, number of segments in each path, and in the case of $ ./python -m timeit \
-s 'from pathlib import Path; p0 = Path("foo/bar"); p1 = Path("foo")' \
'str(p0.relative_to(p1))'
10000 loops, best of 5: 20.3 usec per loop # before
50000 loops, best of 5: 9.13 usec per loop # after
$ ./python -m timeit \
-s 'from pathlib import Path; p0 = Path("foo/bar"); p1 = "foo"' \
'str(p0.relative_to(p1))'
10000 loops, best of 5: 20.4 usec per loop # before
20000 loops, best of 5: 14.5 usec per loop # after
$ ./python -m timeit \
-s 'from pathlib import Path; p0 = Path("foo/bar"); p1 = Path("foo")' \
'p0.is_relative_to(p1)'
50000 loops, best of 5: 9.01 usec per loop # before
50000 loops, best of 5: 4.15 usec per loop # after
$ ./python -m timeit \
-s 'from pathlib import Path; p0 = Path("foo/bar"); p1 = "foo"' \
'p0.is_relative_to(p1)'
50000 loops, best of 5: 9.04 usec per loop # before
50000 loops, best of 5: 8.91 usec per loop # after |
@pitrou Sorry for tagging, but based on contributor history, would you mind giving a quick review? |
Thanks for reviewing @Jason-Y-Z! |
Avoid unnecessary calls to
with_segments()
. This makes bothis_relative_to()
andrelative_to()
faster when passed aPurePath
object, and makesrelative_to()
faster when passed another kind of path-like object (like astr
).Also, use
_from_parsed_parts()
inrelative_to()
to return a pre-parsed path. Operations likestr(p.relative_to(q))
are faster as a result.pathlib.PurePath.[is_]relative_to()
#111429