+ 6
Best way to get elapsed time? (ms)
Hi! Does anyone know of a good (the best if you know) way to determine an elapsed time in milliseconds? It is for a console game I am currently making. I have the following which I have cobbled together from reading various materials online but am not sure if its great. I mean it works. But does anyone know if there is a better way https://code.sololearn.com/cD7BoqGQ0Zjh/?ref=app
13 Answers
+ 15
// I haven't used chrono before but here's what I've used before for timing
#include <windows.h>
// Initialise
LARGE_INTEGER start, end, frequency;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&start);
// Do stuff here
// Calculate time taken
QueryPerformanceCounter(&end);
double timeTakenInSeconds =
(end.QuadPart - start.QuadPart ) / (double)frequency.QuadPart;
+ 14
Is this going to be on Windows? If so, try using windows.h
+ 13
@Rishabh What errors are you getting? Could you post your code again (if it's not too much trouble)?
+ 12
(some extra info)
The clock() function returns CLOCKS_PER_SEC resolution
The value for CLOCKS_PER_SEC is usually only 1000, therefore the clock() function is only accurate to 0.001 seconds
So don't use it for precision timing!
+ 12
@Rishabh Your output is in seconds, not ms! Also, your loop finishes within 0.001 seconds. Try setting your loop condition higher to 10000000 đ
+ 12
@Rishabh (got your name right this time đ) No problem
+ 5
fyi: using typedef as i need to store start ticks to a class member.
+ 5
Thanks! I will have to research that! I am guessing frequency is a time segment such as milliseconds thus the division to get time taken.
It may prove useful! It may even be faster than the method I am trying!
** Eventually I want to port this game over to SDL and am trying to make it as modular (and as fast) as possible **
+ 4
I am using windows.h I already have a window class setup which is tied into a finite state machine. I think you meant use that for the game as I cant find a reference made to a timer function in windows.h
I made a better timer. I think it should suit my needs. maybe. Do you think this will work well?
I will create a timer at the start of the program. Then store the results of getTIcks() in various class members in a variable called lastTick to base things like enemy movement off.
with some code to check time since last move like: if(lastTick - getTick() < 1000) { enemy.move(); }
What do you think?
https://code.sololearn.com/c2FByP9IIsbx/?ref=app
+ 4
Not errors but it is giving 0 ms for the execution of the program
https://code.sololearn.com/c2mOXWhgh0TH/?ref=app
+ 3
Hey @jafca
I removed my post because it was not giving me output in code playground.
Can you explain the reason.
Thanks for your help.
+ 3
Thanks @jafca finally it worked
and btw my name is rishabh
+ 2
Thanks đđ