Savefig taking a long time from command line

I’ve written a short script that makes small images of text sequences and colours them according to some metric:

When I run an example from an IDE, the program runs the attached example in 198 ms ± 18.7 ms per loop. For the same example is executed from the command line there’s a significant decrease in performance, slowing to 2.54 s ± 44.9 ms per loop.

For anything much longer than the example given, making an image becomes so slow as to render the program pointless. I think this is because savefig is trying to capture all the individual text artists in drawing the bounding box for saving: to get the colours correct, the script is based on this example. So, I’m wondering:

  1. why is there such a significant difference between how long the script takes (although I think I mostly know why)
  2. what can be done to speed up the saving of the image generated?

I suspect the reason for 2) is mainly because savefig has to construct the bbox from all the text artists in the figure of which there can be quite a few as each letter is written individually, but I still wouldn’t expect this to cause an 11x slowdown for such a small image.

Python 3.10.12
Matplotlib 3.8.0

Hi @csbrasnett are you able to share a simple script that demonstrates the problem? It is difficult to suggest what to change if we do not know exactly what you are currently doing.

You might see a speedup of you upgrade to Matplotlib v3.9, which is available to install with pip.

1 Like

Hi @rcomer thanks for the suggestion, v3.9 does speed it up significantly. I tried an input file with >2000 letters as a test and it generated what I wanted in < 1 min, where ~200 letters was not finishing before I killed it before.

The code’s here if you’d still like to take a look. I don’t know what significantly changed between 3.8 and 3.9, but I guess it’d be useful to know still!

1 Like

I was thinking of this change, which removed redundant calls to get the bbox of artists on an axes.

Edit: though I’m not sure that this one PR could account for a >10x improvement.

1 Like