下面给出了从文件中读取值并绘制它们的代码。我正在阅读大约36000个值。我正在使用matplotlib来绘制它们。如果值低于某个阈值,我将删除并旋转我为绘图制作的网格。
def readdata():
global mul
global fig
global S
global flag
global k
global line_number
global readcount
global angle_deviate
global true_counter
global fail_flag
global loop_count
global ts
global xlist
global ylist
while k<S:
line_number=line_number+1
line=linecache.getline("data.txt", line_number)
if line_number==1:
x=float(line)*math.cos(0)
y=float(line)*math.sin(0)
xlist.append(300+x)
ylist.append(300+y)
else:
x=float(line)*math.cos((readcount-1)*mul/samp_rate)
y=float(line)*math.sin((readcount-1)*mul/samp_rate)
xlist.append(300+x)
ylist.append(300+y)
plt.plot(xlist, ylist, lw=1, color='#ee8d18')
if true_counter <(samp_rate*t[k]): #true counter to determine if the stage is complete or not
if k<S-1 and k!=S-1:
if p[k]<float(line):
true_counter=true_counter+1
fail_flag=1
point=plt.plot(300+x, 300+y, '.', markersize=3, color='#ee8d18')
loop_count+=1
pts.append(point)
readcount+=1
plt.pause(0.1) #first pause in plotting for 0.1 seconds
continue
else:
readcount+=1
true_counter=0
point=plt.plot(300+x, 300+y, '.', markersize=3, color='#ee8d18')
loop_count+=1
pts.append(point)
plt.pause(0.1) #first pause in plotting for 0.1 seconds
deleteplot(k, fail_flag, loop_count)
if k==S-1:
if p[k]<float(line):
readcount+=1
true_counter=true_counter+1
x=float(line)*math.cos((readcount-1)*mul/samp_rate)
y=float(line)*math.sin((readcount-1)*mul/samp_rate)
point=plt.plot(300+x, 300+y, '.', markersize=3, color='#ee8d18')
loop_count+=1
pts.append(point)
plt.pause(0.1) #first pause in plotting for 0.1 seconds
continue
else:
readcount+=1
true_counter=0
point=plt.plot(300+x, 300+y, '.', markersize=3, color='#ee8d18')
loop_count+=1
pts.append(point)
plt.pause(0.1) #first pause in plotting for 0.1 seconds
deleteplot(k, fail_flag, loop_count)
else:
true_counter=0
k+=1
fail_flag=0
line_number=line_number-1
loop_count=0
i=0
while i<S+1:
cumulative_theta[i]=rotate_theta[i]
i+=1
问题是这段代码像任何东西一样使用内存。它从30MB开始,一小时左右就达到260-300 MB。如何减少内存使用量?我还能做些什么来减少CPU负载和内存中断?
答案 0 :(得分:0)
我怀疑你想要这样的东西:
from matplotlib import pyplot as plt
# make figure + axes
fig, ax = plt.subplots(1, 1)
# make base line
ln, = ax.plot([], [], 'r')
for j in range(50):
# get current data
x_data = list(ln.get_xdata())
y_data = list(ln.get_ydata())
# append new data, or do what ever you want to it
x_data.append(j)
y_data.append(j * j)
# to keep just last n points, x_data = x_data[-n:]
# set data of existing line
ln.set_xdata(x_data)
ln.set_ydata(y_data)
# auto-scale the view limits
ax.relim()
ax.autoscale()
# force the canvas to redraw
plt.draw()
# pause to give the gui time to refresh
plt.pause(.1)
不会在内部循环中创建任何新对象,只需更新现有对象。
我还会研究animation
模块示例。