The Allegro Wiki is migrating to github at https://github.com/liballeg/allegro_wiki/wiki

Accurate timing

From Allegro Wiki
Jump to: navigation, search
Documentation.png
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.


<highlightSyntax language="cpp">// plat.h // Platform compatibility


  1. ifdef __linux__
  2. include <stdint.h>
  3. include <sys/time.h>
  4. include <signal.h>
  5. define DEBUG_BREAK() raise(SIGTRAP)

typedef timeval TimeType;

  1. endif
  1. ifdef __MINGW32__
  2. include <stdint.h>
  3. include <winalleg.h>

typedef LARGE_INTEGER TimeType;

  1. endif
  1. ifdef _MSC_VER
  2. include <winalleg.h>
  3. undef min
  4. undef max
  5. 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;

  1. endif

TimeType GetNow(); TimeType GetDiff(TimeType _then, double& dtime); void Sleep(uint32_t msecs);

// The end

</highlightSyntax>

<highlightSyntax language="cpp">// plat.cpp // Platform compatibility layer

  1. include "tinparty.h"

using namespace std;

  1. 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);

}

  1. endif
  1. 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);

}

  1. endif

// The end

</highlightSyntax>