2014-03-25 1 views
0

Я пытаюсь написать класс, который сможет использовать события QueryPerformanceCounter в C++. Идея состоит в том, что вы создаете объект таймера, предоставляете функцию времени в двойном формате и рассчитываете до тех пор, пока это время не пройдет мимо и не начнет делать потом. Этот класс идеально будет использоваться для синхронизации вещей в игре (например, таймер, который составляет 60 раз в секунду). Когда я компилирую этот код, он просто печатает 0 на консоль, казалось бы, навсегда. Но я заметил какую-то ошибку, которую я не понимаю. Если я нажму на полосу прокрутки окна консоли и удерживаю ее, таймер будет правильно подсчитываться. Если я, например, вхожу в 5.0, то быстро нажмите и удерживайте полосу прокрутки в течение 5 секунд или дольше, когда я отпустил программу, напечатает «Done !!!». так почему он не учитывает должным образом, когда я просто позволяю ему печатать прошедшее время на консоли? есть ли глюк с печатью вещей на консоль или что-то не так с моим временным кодом? Ниже приведен код:Ошибка синхронизации событий синхронизации 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 количество микросекунд, прошедших с Fisrt вызова 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

 Смежные вопросы

  • Нет связанных вопросов^_^