Sys_DoubleTime () - Condensed Windows

Post tutorials on how to do certain tasks within game or engine code here.
Post Reply
Baker
Posts: 3666
Joined: Tue Mar 14, 2006 5:15 am

Sys_DoubleTime () - Condensed Windows

Post by Baker »

Sys_FloatTime in the Quake source release can act badly on multi-core machines and some other circumstances (overclocking?). This is a Windows-specific problem.

The result is demos running too fast or too slow.

This is the replacement for Sys_FloatTime thinned out ...

Code: Select all

#include <limits.h>		// LONG_MAX

static double	pfreq;
static BOOL		hwtimer = FALSE;

void Sys_InitDoubleTime (void)
{
	__int64	freq;

	if (QueryPerformanceFrequency ((LARGE_INTEGER *)&freq) && freq > 0)
	{
		// hardware timer available
		pfreq = (double)freq;
		hwtimer = TRUE;
	} else
	{
		// make sure the timer is high precision, otherwise NT gets 18ms resolution
		timeBeginPeriod (1);
	}
}

double Sys_DoubleTime (void)
{
	__int64		pcount;
	static	__int64	startcount;
	static	DWORD	starttime;
	static  BOOL	first = TRUE;
	DWORD	now;

	if (hwtimer)
	{
		QueryPerformanceCounter ((LARGE_INTEGER *)&pcount);
		if (first)
		{
			first = FALSE;
			startcount = pcount;
			return 0.0;
		}
		// TODO: check for wrapping
		return (pcount - startcount) / pfreq;
	}

	now = timeGetTime ();

	if (first)
	{
		first = FALSE;
		starttime = now;
		return 0.0;
	}

	if (now < starttime) // wrapped?
		return (now / 1000.0) + (LONG_MAX - starttime / 1000.0);

	if (now - starttime == 0)
		return 0.0;

	return (now - starttime) / 1000.0;
}
The night is young. How else can I annoy the world before sunsrise? 8) Inquisitive minds want to know ! And if they don't -- well like that ever has stopped me before ..
Post Reply