Accurate timing
From Allegro Wiki
This code snippet requires documentation. If you understand how this code is intended to be used, please help Allegro by documenting it. Once the snippet is fully documented, you may remove this tag.
// plat.h // Platform compatibility #ifdef __linux__ # include <stdint.h> # include <sys/time.h> # include <signal.h> # define DEBUG_BREAK() raise(SIGTRAP) typedef timeval TimeType; #endif #ifdef __MINGW32__ # include <stdint.h> # include <winalleg.h> typedef LARGE_INTEGER TimeType; #endif #ifdef _MSC_VER # include <winalleg.h> # undef min # undef max # define DEBUG_BREAK() DebugBreak() typedef __int8 int8_t; typedef unsigned __int8 uint8_t; typedef __int16 int16_t; typedef unsigned __int16 uint16_t; typedef __int32 int32_t; typedef unsigned __int32 uint32_t; typedef __int64 int64_t; typedef unsigned __int64 uint64_t; typedef LARGE_INTEGER TimeType; #endif TimeType GetNow(); TimeType GetDiff(TimeType _then, double& dtime); void Sleep(uint32_t msecs); // The end
// plat.cpp
// Platform compatibility layer
#include "tinparty.h"
using namespace std;
#ifdef __linux__
TimeType GetNow()
{
timeval now;
gettimeofday(&now, NULL);
return (TimeType) now;
}
TimeType GetDiff(TimeType _then, double& dtime)
{
timeval then = (timeval) _then;
timeval now;
gettimeofday(&now, NULL);
timeval diff;
diff.tv_sec = now.tv_sec - then.tv_sec;
diff.tv_usec = now.tv_usec - then.tv_usec;
while(diff.tv_usec < 0)
{
diff.tv_sec--;
diff.tv_usec = 1000000 + now.tv_usec - then.tv_usec;
}
dtime = diff.tv_sec;
dtime += (double) diff.tv_usec / 1e6;
return (TimeType) now;
}
void Sleep(uint32_t msecs)
{
timeval t;
t.tv_sec = msecs / 1000;
t.tv_usec = 1000 * (msecs % 1000);
select(0, NULL, NULL, NULL, &t);
}
#endif
#if __MINGW32__ || _MSC_VER
static LARGE_INTEGER pers;
TimeType GetNow()
{
LARGE_INTEGER now;
QueryPerformanceFrequency(&pers);
QueryPerformanceCounter(&now);
return (TimeType) now;
}
TimeType GetDiff(TimeType _then, double& dtime)
{
LARGE_INTEGER then = (LARGE_INTEGER) _then;
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
LARGE_INTEGER diff;
diff.QuadPart = now.QuadPart - then.QuadPart;
dtime = (double) diff.QuadPart / pers.QuadPart;
return (TimeType) now;
}
void Sleep(uint32_t milliseconds)
{
Sleep((unsigned long) milliseconds);
}
#endif
// The end
