2015-09-02 112 views
0

我正在製作一個現場劇情。我從頻譜分析儀獲取數據,該頻譜分析儀以特定頻率給出了我的數值。但是程序運行時間越長越慢。 所以我希望你有一些想法。在運行時我還看着我的活動監視器,並且RAM根本沒有滿。Python - 優化劇情代碼

我試圖評論出ctf = ax.contourf(a, b, B, cmap=cma)這是負責繪圖,如果它不需要繪製它如此之快。但我需要這樣的情節,所以不是繪畫不是一個解決方案。

ax = plt.subplot(111, polar = True)瞭解更多信息。

這裏是我的代碼:

while True : 
trace = inst.query(':TRACe:DATA? TRACE1').partition(' ')[2][:-2].split(', ')# the first & last 2 entries are cut off, are random numbers 

for value in trace : #write to file 
    f.write(value) 
    f.write('\n') 

try : #looking if data is alright 
    trace = np.array(trace, np.float) 
except ValueError: #if a ValueError is raised this message is displayed but the loop won't break and the piece is plotted in one color (green) 
    print'Some wrong data at the', i+1, 'th measurement' 
    longzeroarray = np.zeros(801) 

    a = np.linspace(i*np.pi/8-np.pi/16, i*np.pi/8+np.pi/16, 2)#Angle, circle is divided into 16 pieces 
    b = np.linspace(start -scaleplot, stop,801) #points of the frequency + 200 more points to gain the inner circle 
    A, B = np.meshgrid(a, longzeroarray) 
    cma = ListedColormap(['w']) 

    #actual plotting 
    ctf = ax.contourf(a, b, B, cmap=cma) 

    xCooPoint = i*np.pi/8 + np.pi/16 #shows the user the position of the plot 
    yCooPoint = stop 
    ax.plot(xCooPoint, yCooPoint, 'or', markersize = 15) 

    xCooWhitePoint = (i-1) * np.pi/8 + np.pi/16 #this erases the old red points 
    yCooWhitePoint = stop 
    ax.plot(xCooWhitePoint, yCooWhitePoint, 'ow', markersize = 15) 


    plt.draw() 
    time.sleep(60) #delaying the time to give analyser time to give us new correct data in the next step 
    i +=1 
    continue 

maximasearch(trace,searchrange) 

trace = np.insert(trace,0,zeroarray) 
a = np.linspace(i*np.pi/8+np.pi/16-np.pi/8, i*np.pi/8+np.pi/16, 2)#Angle, circle is divided into 16 pieces 
b = np.linspace(start -scaleplot, stop,801) #points of the frequency + 200 more points to gain the inner circle 
A, B = np.meshgrid(a, trace) 

#actual plotting 
ctf = ax.contourf(a, b, B, cmap=cm.jet, vmin=-100, vmax=100) 

xCooPoint = i*np.pi/8 + np.pi/16 #shows the user the position of the plot 
yCooPoint = stop 
ax.plot(xCooPoint, yCooPoint, 'or', markersize = 15) 

xCooWhitePoint = (i-1) * np.pi/8 + np.pi/16 #this erases the old red points 
yCooWhitePoint = stop 
ax.plot(xCooWhitePoint, yCooWhitePoint, 'ow', markersize = 15) 


plt.draw() 
i+=1 

那是劇情的樣子,並與每一個新的臺階圓的一條新繪製。 enter image description here

編輯

我在這裏找到以下問題上堆棧溢出:real-time plotting in while loop with matplotlib

我覺得跟22個Upvotes的答案可能是有益的。有沒有人曾經使用blit?我還不知道如何將它與我的代碼結合起來。

http://wiki.scipy.org/Cookbook/Matplotlib/Animations

+0

blitting讓你更新和藝術家,只重繪_that_藝術家,可以節省大量的渲染時間。 – tacaswell

回答

0

我想再次回答我自己的問題。

優化代碼的最佳方法是使用模2 * pi計算徑向值。

我改變了我的代碼位:

a = np.linspace((i*np.pi/8+np.pi/16-np.pi/8)%(np.pi*2), (i*np.pi/8+np.pi/16)%(np.pi*2), 2) 

問題之前是Python中還繪製所有的舊件,因爲很明顯的是仍然存在,但只有在新繪製的數據塊層。所以儘管你沒有看到舊的繪圖數據,但它仍然被繪製。現在只有從0到2pi的圓被重繪。