2011-01-05 35 views
0

在我的遊戲中,我需要一個秒錶來測量並顯示已用時間。QTime QTimer超時()驅動的秒錶具有較高的CPU使用率

爲此,我做了一個簡單的小工具:

ZuulStopwatchWidget::ZuulStopwatchWidget(QWidget *parent) : 
    QWidget(parent) 
{ 
     num = new QLCDNumber(this); // create the display 
     num->setDigitCount(9); 

     time = new QTime(); 
     time->setHMS(0,0,0,0); // set the time 

     timer = new QTimer(this); 

     connect(timer, SIGNAL(timeout()), this, SLOT(showTime())); 
     i=0; 
     QString text = time->toString("hh:mm:ss"); 
     num->display(text); 
     //num->setStyleSheet("* { background-color:rgb(199,147,88);color:rgb(255,255,255); padding: 7px}}"); 
     num->setSegmentStyle(QLCDNumber::Flat); //filled flat outline 
     //setStyleSheet("* { background-color:rgb(236,219,187)}}"); 

     layout = new QVBoxLayout(this); 
     layout->addWidget(num); 
     setMinimumHeight(70); 
} 

ZuulStopwatchWidget::~ZuulStopwatchWidget() 
{ 
    // No need to delete any object that has a parent which is properly deleted. 

} 
void ZuulStopwatchWidget::resetTime() 
{ 
    time->setHMS(0,0,0); 
    QString text = time->toString("hh:mm:ss"); 
    num->display(text); 
    i=0; 
    stopTime(); 
} 

void ZuulStopwatchWidget::startTime() 
{ 
    //flag=0; 
    timer->start(1); 
} 

void ZuulStopwatchWidget::stopTime() 
{ 
    timer->stop(); 
} 


void ZuulStopwatchWidget::showTime() 
{ 
    QTime newtime; 
     //if(flag==1) 
       //i=i-1; 
    i=i+1; 
    newtime=time->addMSecs(i); 
    QString text = newtime.toString("mm:ss:zzz"); 
    num->display(text); 
} 

但是當我運行我的遊戲CPU使用率在13%左右在2,5Ghz I5。我知道這不是問題,但它確實是一個愚蠢的時鐘可笑。

我這樣做是完全錯誤還是這種常見做法?!

非常感謝提前。

+0

你知道哪些功能特別是造成CPU時間的尖峯?你能分析你的代碼等嗎? – chrisaycock 2011-01-05 01:49:42

+0

我絕對相信這個秒錶小部件會導致問題。分析只會導致方法ml_set_interrupts_enabled(mach內核)占主導地位。我想這些是由定時器發送的超時信號。這個時鐘的精度爲毫秒,但仍然有1000箇中斷一秒不是CPU密集的嗎? (我的15歲卡西歐手錶可以在最小的電池上使用一年) – user558802 2011-01-05 02:06:06

回答

2

啓動(1)設置定時器觸發每毫秒

然後要格式化字符串並打印屏幕比屏幕16倍速度上可能更新反正