8000 Cache realpath resolution in font_manager. · matplotlib/matplotlib@d7157b4 · GitHub
[go: up one dir, main page]

Skip to content

Commit d7157b4

Browse files
committed
Cache realpath resolution in font_manager.
This shaves off ~33% runtime from ```python from pylab import * import timeit tx = figtext(.5, .5, "foo\nbar baz") gcf().canvas.draw() gcf().patch.set_visible(False) r = gcf()._cachedRenderer n, t = timeit.Timer(lambda: tx.draw(r)).autorange(); print(t / n, n, t) ``` because previously the calls to realpath were not cached and filesystem access is slow. (The font cache is likely already in trouble if fonts move in the filesystem within the execution of a program given that there are other layers of cache, so I wouldn't overly worry about that. At best we may want to expose a manual function to invalidate all caches if someone really runs into that problem.)
1 parent 86f1ea7 commit d7157b4

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

lib/matplotlib/font_manager.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,11 @@
161161
]
162162

163163

164+
@lru_cache(64)
165+
def _cached_realpath(path):
166+
return os.path.realpath(path)
167+
168+
164169
def get_fontext_synonyms(fontext):
165170
"""
166171
Return a list of file extensions extensions that are synonyms for
@@ -1308,10 +1313,9 @@ def findfont(self, prop, fontext='ttf', directory=None,
13081313
rc_params = tuple(tuple(rcParams[key]) for key in [
13091314
"font.serif", "font.sans-serif", "font.cursive", "font.fantasy",
13101315
"font.monospace"])
1311-
filename = self._findfont_cached(
1316+
return self._findfont_cached(
13121317
prop, fontext, directory, fallback_to_default, rebuild_if_missing,
13131318
rc_params)
1314-
return os.path.realpath(filename)
13151319

13161320
@lru_cache()
13171321
def _findfont_cached(self, prop, fontext, directory, fallback_to_default,
@@ -1382,7 +1386,7 @@ def _findfont_cached(self, prop, fontext, directory, fallback_to_default,
13821386
else:
13831387
raise ValueError("No valid font could be found")
13841388

1385-
return result
1389+
return _cached_realpath(result)
13861390

13871391

13881392
@lru_cache()
@@ -1411,10 +1415,10 @@ def is_opentype_cff_font(filename):
14111415
def get_font(filename, hinting_factor=None):
14121416
# Resolving the path avoids embedding the font twice in pdf/ps output if a
14131417
# single font is selected using two different relative paths.
1414-
filename = os.path.realpath(filename)
1418+
filename = _cached_realpath(filename)
14151419
if hinting_factor is None:
14161420
hinting_factor = rcParams['text.hinting_factor']
1417-
return _get_font(os.fspath(filename), hinting_factor,
1421+
return _get_font(filename, hinting_factor,
14181422
_kerning_factor=rcParams['text.kerning_factor'])
14191423

14201424

0 commit comments

Comments
 (0)
0