2014-03-25 45 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