python - 为什么 `plt.savefig` 这么慢?我能以某种方式加快速度吗?
问题描述
在不到一秒的时间内创建 100 个图表,但是在转换为 base64 表示而不将它们写入磁盘时将它们写入磁盘需要 10 秒,因此开销在于创建 png/jpg 表示本身,有没有办法加快速度plt.savefig
?
随着bbox_inches="tight"
进一步放缓,所以我想可能有一些方法可以加快速度。
执行时间的所有跳跃都在第 2 步和第 3 步之间(datetime.datetime.now();print
我认为在这种情况下记录就足够了):
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)
解决方案
推荐阅读
- excel - 如何列出数据透视表中的数据透视字段?
- css - Jodit:在编辑器中启动编辑器时文本居中并且背景颜色选择消失
- java - 如何解决 Jsoup Java 中的 HTML 错误 500
- mysql - 如何在 MYSQL 列中保存数据更改
- html - 如何让我的页脚响应而不会出现故障?
- html - bootstrap3 中的内联日期选择器
- c# - WPF 中的 Application.OpenForms[0].InvokeRequired 等效项
- javascript - 如何通过 reactnavigation v5 将参数从一个屏幕传递到另一个屏幕
- javascript - `for/in` 循环包含奇怪的索引
- spring-boot - org.hibernate.boot.model.TypeContributor:未找到提供程序