为什么 `plt.savefig` 如此缓慢?我能以某种方式加快速度吗?
为什么 `plt.savefig` 如此缓慢?我能以某种方式加快速度吗?
在不到一秒钟的时间内创建了100个图表,但是将它们写入磁盘并转换为base64表示形式需要10秒钟,因此开销在于创建png/jpg表示本身,有没有办法加快plt.savefig的速度?\n使用bbox_inches=\"tight\"会进一步减慢速度,所以我猜可能有一些方法可以加快速度。\n执行时间的所有跳变都发生在第2步和第3步之间(在这种情况下,使用datetime.datetime.now();print进行日志记录已经足够):\n
import numpy as np import datetime data = np.random.rand(20, 100) list_base64 = [] path = 'YOUR_PATH' file = "test.jpg" for i in range(data.shape[1]): ct = datetime.datetime.now();print(f"current time: {i} 1", ct) if i==0: ct0=ct plt.plot(data[:,i]) ct = datetime.datetime.now();print(f"current time: {i} 2", ct) plt.savefig(path + file, dpi=10, bbox_inches="tight") ct = datetime.datetime.now();print(f"current time: {i} 3", ct) plt.close() ct = datetime.datetime.now();print(f"current time: {i} 4", ct) plot_file = open(path + file, 'rb') ct = datetime.datetime.now();print(f"current time: {i} 5", ct) base64_string = base64.b64encode(plot_file.read()).decode() ct = datetime.datetime.now();print(f"current time: {i} 6", ct) plot_file.close() ct = datetime.datetime.now();print(f"current time: {i} 7", ct) base64_string = chart_to_base64(plt) ct = datetime.datetime.now();print(f"current time: {i} 8", ct) list_base64.append(base64_string) ct = datetime.datetime.now();print(f"current time: {i} 9", ct) print('loop starts at:', ct0)