winapi - C++ timing events console bug? -
i trying write class able time events using queryperformancecounter in c++. idea create timer object, give function time in double format, , counts until time has passed , stuff afterwards. class ideally used timing things in game ( having timer counts 60 times in second example). when compile code though, prints 0's console, seemingly ever. noticed kind of bug can't understand. if click on scroll bar of console window , hold it, timer counts properly. if enter 5.0 example, click , hold scroll bar 5 seconds or longer, when let go program print 'done!!!'. why doesn't count when let print elapsed time console? there glitch printing things console, or there wrong timing code? below code:
#include <iostream> #include <iomanip> #include "windows.h" using namespace std; int main() { setprecision(10); // tried see if precision in stream problem don't think cout << "hello! lets time something..." << endl; bool timing = 0; // switch turn timer on , off large_integer t1, t2; // timestamps count large_integer freq; // frequency per seccond measuring difference between stamp values queryperformancefrequency(&freq); // gets frequency computer // mil.quadpart = freq.quadpart / 1000; // not used double ellapsedtime = 0, desiredtime; // enter value count in secconds // if entered 4.5 example, should wait 4.5 secconds cout << "enter amount of time wait in seconds (in double format.)!!" << endl; cin >> desiredtime; queryperformancecounter(&t1); // gets first stamp value timing = 1; // switches timer on while(timing) { queryperformancecounter(&t2); // gets stamp value ellapsedtime += (t2.quadpart - t1.quadpart) / freq.quadpart; // measures difference between 2 stamp //values , divides them frequency how many secconds has ellapsed cout << ellapsedtime << endl; t1.quadpart = t2.quadpart; // assigns value of second stamp first one, can measure // difference between them again , again if(ellapsedtime>=desiredtime) // checks if elapsed time bigger or equal desired time, // , if prints done , turns timer off { cout << "done!!!" << endl; timing = 0; // breaks loop } } return 0; }
you should store in ellapsedtime number of microseconds elapsed since fisrt call queryperformancecounter, , should not overwrite first time stamp.
working code:
// gets stamp value queryperformancecounter(&t2); // measures difference between 2 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 elapsed time bigger or equal desired time if(ellapsedtime/1000000.>=desiredtime) { cout << "done!!!" << endl; timing = 0; // breaks loop } be sure read : acquiring high-resolution time stamps
Comments
Post a Comment