2014-03-25 61 views
0

我想寫一個類,它將能夠使用C++中的QueryPerformanceCounter來計時事件。 這個想法是,你創建一個計時器對象,給一個函數一個雙重格式的時間,並且它計數直到那個時間已經過去,然後做了一些事情。這個類最好用於計算遊戲中的時間(例如,計時器在一秒鐘內計數60次)。當我編譯這段代碼時,它只是將0打印到控制檯,看起來永遠都是。但是我發現了一些我無法理解的bug。如果我點擊控制檯窗口的滾動條並按住它,計時器實際上會正確計數。例如,如果我輸入5.0,然後快速單擊並按住滾動條5秒或更長時間,當我放開時,程序將打印'完成!!!'。那麼爲什麼當我只是讓它將經過的時間打印到控制檯時,它不能正確計數呢?有沒有打印到控制檯的問題,或者我的計時代碼有什麼問題?下面是代碼:C++計時事件控制檯錯誤?

#include <iostream> 
#include <iomanip> 
#include "windows.h" 

using namespace std; 



int main() 
{ 

    setprecision(10); // i tried to see if precision in the stream was the problem but i don't think it is 

    cout << "hello! lets time something..." << endl; 

    bool timing = 0;    // a switch to turn the timer on and off 
    LARGE_INTEGER T1, T2;   // the timestamps to count 
    LARGE_INTEGER freq;    // the frequency per seccond for measuring the difference between the stamp values 

    QueryPerformanceFrequency(&freq); // gets the frequency from the computer 

    // mil.QuadPart = freq.QuadPart/1000; // not used 


    double ellapsedtime = 0, desiredtime; // enter a value to count up to in secconds 
    // if you entered 4.5 for example, then it should wait for 4.5 secconds 

    cout << "enter the amount of time you would like to wait for in seconds (in double format.)!!" << endl; 
    cin >> desiredtime; 

    QueryPerformanceCounter(&T1); // gets the first stamp value 
    timing = 1;     // switches the timer on 

    while(timing) 
    { 
     QueryPerformanceCounter(&T2);  // gets another stamp value 
     ellapsedtime += (T2.QuadPart - T1.QuadPart)/freq.QuadPart; // measures the difference between the two stamp 
     //values and then divides them by the frequency to get how many secconds has ellapsed 
     cout << ellapsedtime << endl; 
     T1.QuadPart = T2.QuadPart; // assigns the value of the second stamp to the first one, so that we can measure the 
     // difference between them again and again 

     if(ellapsedtime>=desiredtime) // checks if the elapsed time is bigger than or equal to the desired time, 
     // and if it is prints done and turns the timer off 
     { 
      cout << "done!!!" << endl; 
      timing = 0; // breaks the loop 
     } 
    } 



    return 0; 
} 

回答

0

你應該ellapsedtime存儲,因爲最前一頁調用QueryPerformanceCounter逝去的微秒數,你不應該覆蓋在第一時間戳記。

工作代碼:

// gets another stamp value 
QueryPerformanceCounter(&T2);  

// measures the difference between the two stamp 
ellapsedtime += (T2.QuadPart - T1.QuadPart); 

cout << "number of tick " << ellapsedtime << endl; 
ellapsedtime *= 1000000.; 
ellapsedtime /= freq.QuadPart; 
cout << "number of Microseconds " << ellapsedtime << endl; 

// checks if the elapsed time is bigger than or equal to the desired time 
if(ellapsedtime/1000000.>=desiredtime)   { 
    cout << "done!!!" << endl; 
    timing = 0; // breaks the loop 
} 

請務必閱讀:Acquiring high-resolution time stamps

+0

謝謝您的回答。我已經刪除了打印出當前流逝時間的部分,現在它似乎在正確的時間等待。如果我說等待5.5,它會等待5.5秒,然後打印'完成!'。 – user3023723