Gui(pyqt5)滞后了很多,然后python崩溃了

2024-04-26 12:00:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为我的程序做GUI/控制中心。而且效果很好,但不会持续很长时间。所以,我有两个lcd数字,我想尽快刷新小部件。你知道吗

代码由3部分组成:

  1. 主要
  2. 访问实时数据的函数
  3. Qt设计器中的Gui

首先:

import sys  
from PyQt5 import QtWidgets, QtCore
import untitled  
import tweepy
from configuration import *
import datetime
import pandas as pd
import time
from bitmex import bitmex
from configuration import *
from strategy import Strategy
from trader import Trader
import json
import operator
import sys
from xbt import get_data


class ExampleApp(QtWidgets.QMainWindow, untitled.Ui_MainWindow):

    def __init__(self):
        # 
        super().__init__()
        self.setupUi(self)  # initial UI
        self.pushButton.clicked.connect(self.tweet)  # tweet if pressed

    def tweet(self):

        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)

        api = tweepy.API(auth)

        # If the authentication was successful, you should
        # see the name of the account print out
        print(api.me().name)

        # If the application settings are set for "Read and Write" then
        # this line should tweet out the message to your account's
        # timeline. The "Read and Write" setting is on https://dev.twitter.com/apps
        api.update_status(status='Tweet about last order')

以下是我的观点的主要部分。我认为在main中使用计时器是不好的,但我在StackOverflow上找到了解决方案!

def main():

    app = QtWidgets.QApplication(sys.argv)  
    window = ExampleApp()  
    window.setupUi(window)

    def update_label():
        current_time = str(datetime.datetime.now().time())
        window.label_3.setText(current_time)
    def update_lcd_delta():
        price = str(get_data.get_data_gui())
        window.lcdNumber.display(price)

    def actual_price_lcd():
        actual_price_xbt = str(get_data.price_xbt())
        window.lcdNumber_2.display(actual_price_xbt)

    timer = QtCore.QTimer()
    timer.timeout.connect(update_label) #update_label with current time
    timer.start(10000)  # every 10,000 milliseconds
    timer2 = QtCore.QTimer() #update lcd number with another number
    timer2.timeout.connect(update_lcd_delta)  
    timer2.start(10000)

    timer3 = QtCore.QTimer()
    timer3.timeout.connect(actual_price_lcd)  #update 
    timer3.start(100)

    window.show()  
    app.exec_()  


if __name__ == '__main__':  
    main()  

获取数据的第二部分(工作正常):

import pandas as pd

from bitmex import bitmex
from configuration import *


class get_data():

    def get_data_gui():

        client = bitmex(test=TEST_EXCHANGE, api_key=API_KEY, api_secret=API_SECRET)


        prices_now = pd.DataFrame(client.Trade.Trade_getBucketed(  # get 24 candles with unfinished one
                binSize='1h',
                partial=True,
                symbol='XBTUSD',
                count=24,
                reverse=True
            ).result()[0])
        prices_now.set_index(['close'], inplace=True)
        delta = (prices_now['high'].max() - prices_now['low'].min()) / prices_now['low'].min()

        return delta

    def price_xbt():

        client = bitmex(test=TEST_EXCHANGE, api_key=API_KEY, api_secret=API_SECRET)

        order_book = pd.DataFrame(client.OrderBook.OrderBook_getL2(  # get orderbook
                symbol='XBTUSD',
                depth=2
                # 0 is full depth, using 200-300 we can adjust speed from 0.5 seconds to 0.1 (depends from bitmex)
            ).result()[0])
        print(order_book)
        order_book.set_index(['price', 'size', 'side'], inplace=False)
        price_first_bid = order_book.loc[order_book[order_book.side == 'Buy'].index[0], 'price']
        print(price_first_bid)
        return price_first_bid

据我所知,我有内存泄漏。我该怎么修?你知道吗

这是崩溃信息:

    REGION TYPE                        SIZE    COUNT (non-coalesced) 
===========                     =======  ======= 
Accelerate framework               128K        1 
Activity Tracing                   256K        1 
CG backing stores                 5944K        3 
CG image                            16K        2 
CoreGraphics                         8K        1 
CoreImage                           24K        2 
CoreUI image data                 1372K        7 
CoreUI image file                  404K        4 
Dispatch continuations            8192K        1 
Kernel Alloc Once                    8K        1 
MALLOC                           208.3M       85 
MALLOC guard page                   32K        7 
MALLOC_LARGE (reserved)            128K        1         reserved VM address space (unallocated)
Memory Tag 242                      12K        1 
STACK GUARD                         20K        5 
Stack                             18.0M        5 
VM_ALLOCATE                        108K       10 
VM_ALLOCATE (reserved)            32.0M        1         reserved VM address space (unallocated)
__DATA                            30.4M      397 
__FONT_DATA                          4K        1 
__LINKEDIT                       238.3M      116 
__TEXT                           276.3M      362 
__UNICODE                          564K        1 
mapped file                       57.8M       22 
shared memory                      632K       10 
===========                     =======  ======= 
TOTAL                            878.6M     1047 
TOTAL, minus reserved VM space   846.5M     1047 

我想很快更新这个液晶数字。如何做好?你知道吗


Tags: fromimportselfapidatagetlcddef
1条回答
网友
1楼 · 发布于 2024-04-26 12:00:20

我对它不太了解,但我认为主要的泄漏原因是您每秒与timer3建立客户端连接10次。这是很多试图获取信息的尝试。据我所知,您甚至可以更好地使用单个全局client,我认为泄漏是由于生成太多(每秒10个+每10秒2个)客户端造成的。当你开始的时候做一个可能就行了,我认为当客户不在范围内的时候,有些事情是不会被清除的。你知道吗

延迟的另一个原因是更新和查询数据库的速度很慢,我认为qtimer只是在主线程上运行回调,这意味着等待这些更新也会降低GUI的速度。您需要在一个线程中完成繁重的工作,然后只需使用计时器就可以将您已有的信息发送到GUI。这也可能是导致内存泄漏的原因,但我不知道为什么。你知道吗

不管怎样,我认为你应该解决这两个问题:

  • 重用client变量,不要每次调用都重新生成它。你知道吗
  • 计时器调用的函数需要快速完成任务,让数据库的事情在线程中发生,并使用计时器用线程收集的信息更新GUI。这里的主要问题是timer3,即每秒对该数据库进行10次调用。你知道吗

相关问题 更多 >