1

私は、毎秒入ってくるデータを見るためのリアルタイムモニターを生成するいくつかの単純な python コードを持っています。これは matplotlib を使用しており、メモリ リークがあることを除けば、非常にうまく機能します。スクリプトのメモリ使用量は、1 日の間にゆっくりと増えていきます。私は確かにPythonのプログラミングに慣れていないので、誰かが私がやっていることを見ることができるかどうか疑問に思っていました。助けてくれてありがとう。

import time
import numpy as np
import matplotlib
from matplotlib import figure
import matplotlib.pyplot as plt
import pylab as p
import os
import subprocess as sp
from subprocess import Popen, PIPE

def main():
    #####Initialize the plot#####
    fig = plt.figure()
    ax1 = fig.add_subplot(1,1,1,axisbg='black') #Set up basic plot attributes
    ax1.set_title('Blip Current vs. Time',color='blue')    
    ax1.set_xlabel('Time (hrs)',color='blue')
    ax1.set_ylabel('Blip Current',color='blue')
    for t in ax1.xaxis.get_ticklines(): t.set_color('yellow') 
    for t in ax1.xaxis.get_ticklabels(): t.set_color('yellow') 
    for t in ax1.yaxis.get_ticklines(): t.set_color('white') 
    for t in ax1.yaxis.get_ticklabels(): t.set_color('purple') 
    plt.ion() #Set interactive mode
    plt.show(False) #Set to false so that the code doesn't stop here
    i=0 #initialize counter variable (this will help me to limit the number of points displayed on graph

    ###Update the plot continuously###
    while True: #This is a cheap trick to keep updating the plot, i.e. create a real time data monitor
        blip=Popen('adoIf -vo -6 lxf.blip_b3 dataBarM', shell=True, stdout=PIPE).communicate()[0] #Get data to plot
        hr=float(time.strftime('%H'))
        mins=time.strftime('%M')
        secs=time.strftime('%S')
        secadj=float(secs)/3600
        minadj=float(mins)/60
        currenttime=float(hr+minadj+secadj) #Put time into format for easier plotting, i.e. 21.50 for 9:30 pm
        if currenttime >= 0 and currenttime < 0.22: #Set x range properly when rolling over to midnight
            xmin=0
            xmax=currenttime+.01
        else:
            xmin=currenttime-.22 #Limit data to be displayed, only care about recent past
            xmax=currenttime+.01
        try:
            blip =float(blip) #This throws an error if for some reason the data wasn't received at the top of the while statement
        except ValueError:
            blip=0.0
        if i>300: #Limit displayed points to save memory (hopefully...)
            del ax1.lines[0] #After 300 points, start deleting the first point each time
        else:
            i +=1
        if blip > 6: #Plot green points if current is above threshold
            ax1.plot(currenttime,blip,marker='o', linestyle='--',c='g')
        else: #Plot red points if current has fallen off
            ax1.plot(currenttime,blip,marker='o', linestyle='--',c='r')
        plt.axis([xmin,xmax,None,None]) #Set xmin/xmax to limit displayed data to a reasonable window
        plt.draw()
        time.sleep(2) #Update every 2 seconds

if __name__=='__main__':
    print 'Starting Monitor'
    main()
4

3 に答える 3

3

ユーレカ!私はそれを理解しました(まあ、少なくとも回避策です)。while ループから ax1.plot コマンドを取り出し、代わりに「set_xdata」および「set_ydata」コマンドを fig.canvas.draw() コマンドと一緒に使用します。助けてくれたみんな、特に ax.plot コマンドが呼び出すたびに新しいオブジェクトを作成することを指摘してくれた reptilicus に感謝します。

プロットする x 値と y 値が配列に格納され、各配列の最初の要素が while ループの反復ごとに削除されます (特定の数の点がプロットされた後、その数は を使用してコードで指定されます)。単純なインデックス番号 i)。メモリ使用量は横ばいで、CPU 使用量は少なくなります。コードは次のとおりです。

def main():
    #####Initialize the plot attributes#####
    fig = plt.figure()
    ax1 = fig.add_subplot(1,1,1, axisbg='black')#Set up basic plot attributes
    ax1.set_title('Blip Current vs. Time',color='blue')    
    ax1.set_xlabel('Time (hrs)',color='blue')
    ax1.set_ylabel('Blip Current',color='blue')
    for t in ax1.xaxis.get_ticklines(): t.set_color('yellow') 
    for t in ax1.xaxis.get_ticklabels(): t.set_color('yellow') 
    for t in ax1.yaxis.get_ticklines(): t.set_color('white') 
    for t in ax1.yaxis.get_ticklabels(): t.set_color('purple') 
    plt.ion() #Set interactive mode
    plt.show(False) #Set to false so that the code doesn't stop here
    i=0 #initialize counter variable (this will help me to limit the number of points displayed on graph

    ###Initialize x values####
    times=[] #Create blank array to hold x values
    hr=float(time.strftime('%H')) #Hours
    mins=time.strftime('%M') #Minutes
    secs=time.strftime('%S') #Seconds
    secadj=float(secs)/3600
    minadj=float(mins)/60
    currenttime=float(hr+minadj+secadj) #Put time into format for easier plotting, i.e. 21.50 for 9:30 pm
    times.append(currenttime) #Add first x value to x value array
    if currenttime >= 0 and currenttime < 0.22: #Set x range properly when rolling over to midnight
        xmin=0
        xmax=currenttime+.01
    else:
        xmin=currenttime-.22 #Limit data to be displayed, only care about recent past
        xmax=currenttime+.01

    ###Initialize y values###
    blipcur=[] #Create blank array to hold y values
    blip=Popen('adoIf -vo -6 lxf.blip_b3 dataBarM', shell=True, stdout=PIPE).communicate()[0] #Get first datapoint for plot
    try:
        blip =float(blip) #This throws an error if for some reason the data wasn't received at the top of the while statement
    except ValueError:
        blip=0.0
    blipcur.append(blip) #Add first y value to y value array

    ###Initialize plot###
    line1, = ax1.plot(times, blipcur, 'g-', marker='o')

    ###Update the plot continuously###
    while True: #This is a cheap trick to keep updating the plot, i.e. create a real time data monitor
        hr=float(time.strftime('%H')) #Get new x data for plotting (get current time)
        mins=time.strftime('%M')
        secs=time.strftime('%S')
        secadj=float(secs)/3600
        minadj=float(mins)/60
        currenttime=float(hr+minadj+secadj) #Put time into format for easier plotting, i.e. 21.50 for 9:30 pm
        times.append(currenttime) #Add latest point to x value array
        if currenttime >= 0 and currenttime < 0.22: #Set x range properly when rolling over to midnight
            xmin=0
            xmax=currenttime+.01
        else:
            xmin=currenttime-.22 #Limit data to be displayed, only care about recent past
            xmax=currenttime+.01

        blip=Popen('adoIf -vo -6 lxf.blip_b3 dataBarM', shell=True, stdout=PIPE).communicate()[0] #Get new y data for plotting
        try:
            blip =float(blip) #This throws an error if for some reason the data wasn't received from previous line of code
        except ValueError: #Just set to zero if there was some temporary error
            blip=0.0
        blipcur.append(blip) #Add latest point to y value array

        if i>285: #Limit data points shown on graph.  Saves memory.
            del blipcur[0] #Delete first element in y value array (oldest/first plotted point)
            del times[0] #Delete first element in x value array
        else:
            i +=1 #Only want to keep making number bigger until I get over the threshold for # points I want, then why bother

        line1.set_xdata(times) #Set x data for plot from x value array
        plt.axis([xmin,xmax,-2,50]) #Set xmin/xmax to limit displayed data to a reasonable window
        line1.set_ydata(blipcur) #Set y data for plot from y value array
        fig.canvas.draw() #Update plot
        time.sleep(2.6) #Update every 2.6 seconds

if __name__=='__main__':
    print 'Starting Monitor'
    main()
于 2013-07-08T11:16:11.103 に答える
2

毎回図をクリアする必要があると確信しています。そうしないと、matplotlib が大量の新しいオブジェクトを作成し続け、ガベージ コレクションが行われなくなります。次のようなものを試してください:

fig.clf()

while ループ内の最初のものとして。

于 2013-07-08T01:56:39.667 に答える