在不到一秒的时间内创建 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)