Timing, How Does Your App Fare?

Miscellaneous Forums/General Discussion/Timing, How Does Your App Fare?

Kuron's repost of Mark's is here:

http://www.blitzbasic.com/Community/posts.php?topic=48890

The Retro64 method (modified by me a bit) is like this (excuse crap indenting):

	;timing vars
	Global FRAMERATE# = 200 ;Float on purpose so calcs end up as float
	Global MS# = 1000.0/FRAMERATE ;use .0 to ensure float is returned ;milliseconds per frame float
	Global LastTime%
	Global NumTicks#
	Global LastNumTicks#

Function InitTimingVars()
	;set a first value for LastTime (it will be used in the main loop)
	LastTime = MilliSecs()/MS
	NumTicks = 0
	LastNumTicks = 1	
End Function

;Main code below

InitTimingVars()
Loop=1
Repeat
			;for our purposes, a tick is based on FRAMERATE
			;get in the time and make sure at least 1 tick expired
			Repeat
				TmpMS = MilliSecs()/MS
		
				;little sanity check here in case the timer flips back to 0 :)
				If TmpMS < LastTime Then LastTime = TmpMS - LastNumTicks
		
				NumTicks = TmpMS - LastTime
			Until NumTicks > 0
			LastTime = TmpMS
			;account for when the user alt-tabs :)
			If NumTicks > 500 Then NumTicks = LastNumTicks
			LastNumTicks = NumTicks		
							
    ;now we do the logic loop ... from 1 not 0!
    For i = 1 To NumTicks
       ;some game logic code (no drawing)
    Next

    ;now the drawing code followed by flip

Until Loop=0


I've refined this since though using this rad doc: http://www.gaffer.org/articles/Timestep.html by adding a final floating point based iteration, bit like delta timing.

Also a lot of people forget to do this, but if you pause the game or lose focus, always call InitTimingVars() again otherwise the game will leap ahead, although the code above limits the jump if it's >500 times. I've made this value a lot smaller since though due to having lots of tracking of possible breaks in gameplay.