import os
figure_save_path = "file_fig_test"
import warnings
warnings.filterwarnings("error")
import numpy as np
np.random.seed(0)
import matplotlib.pyplot as plt
from PIL import Image
import time
num = 100
gif_frames = []
open_time = []
save_time = []
plot_time = []
for i in range(num):
#图形绘制
start_time = time.time()
plt.scatter(np.random.random(), np.random.random())
end_time = time.time()
plot_time.append(end_time-start_time)
#创建图形保存文件夹
if not os.path.exists(figure_save_path):
os.makedirs(figure_save_path)
else:
pass
#保存图形
start_time = time.time()
plt.savefig(os.path.join(figure_save_path, str(i) + ".jpg"))
end_time = time.time()
save_time.append(end_time-start_time)
#打开图形
start_time = time.time()
img = Image.open(os.path.join(figure_save_path, str(i) + ".jpg"))
end_time = time.time()
open_time.append(end_time-start_time)
gif_frames.append(img)
print("动画绘制开始")
start_time = time.time()
gif_frames[0].save("test.gif",
save_all=True, append_images=gif_frames[1:], duration=200, loop=0)
end_time = time.time()
print("动画绘制完成,用时:", round(end_time-start_time, 6))
print("平均动画绘制完成,用时:", round((end_time-start_time)/num, 6))
print("平均图形绘制用时:", round(sum(plot_time)/len(plot_time), 6))
print("平均图形保存用时:", round(sum(save_time)/len(save_time), 6))
print("平均图形打开用时:", round(sum(open_time)/len(open_time), 6))
动画绘制开始
动画绘制完成,用时: 3.61503
平均动画绘制完成,用时: 0.03615
平均图形绘制用时: 0.004437
平均图形保存用时: 0.146415
平均图形打开用时: 0.000287
那我们再看看随着图片数量的增长,绘制动画的用时变化
gif_time = []
for i in range(20, 100):
new_frames = gif_frames[:i]
start_time = time.time()
new_frames[0].save(str(i)+".gif",
save_all=True, append_images=gif_frames[1:], duration=200, loop=0)
end_time = time.time()
gif_time.append(end_time-start_time)
print("finished:", str(i))