这是一个让我疯狂的非常奇怪的问题......
我使用Sleep()函数来设置我的游戏帧速率,我只是执行游戏循环并且我在最后等待几毫秒来调整到每帧~16.6 ms。为此,我创建了自己的等待函数(多平台,但问题只发生在_WIN32上):
// Wait for some milliseconds (stop program execution)
static void Wait(float ms)
{
//#define USE_BUSY_WAIT_LOOP
#if defined(USE_BUSY_WAIT_LOOP)
double prevTime = GetTime();
double nextTime = 0.0;
// Busy wait loop
while ((nextTime - prevTime) < ms/1000.0f) nextTime = GetTime();
#else
#if defined _WIN32
Sleep((unsigned int)ms);
#elif defined __linux__
struct timespec req = { 0 };
time_t sec = (int)(ms/1000.0f);
ms -= (sec*1000);
req.tv_sec = sec;
req.tv_nsec = ms*1000000L;
// NOTE: Use nanosleep() on Unix platforms... usleep() it's deprecated.
while (nanosleep(&req, &req) == -1) continue;
#elif defined __APPLE__
usleep(ms*1000.0f);
#endif
#endif
}
为了避免包含windows.h,我只将Sleep()函数定义为:
#if defined(_WIN32)
void __stdcall Sleep(unsigned long msTimeout);
#endif
问题:当我使用MinGW32(GCC 5.3.0)编译此代码时,当我使用MSVC进行编译时,Sleep()似乎比传递给函数的毫秒更长(几乎是两倍)(Visual Studio Community 2015) ,有时它工作正常,有时不行。最奇怪的是,当它工作时,如果我执行以前不工作的MinGW32版本......那么它们工作正常!疯了......
根据我的理解,问题应该与某些运行时库使用,操作系统相关(尝试使用Windows 10 64位)有关。注意到,当工作正常时,如果正在探索进程,dwm.exe控制第二个线程(等待链) - 不确定它意味着什么 - 当失败时,该进程不可用。
仅供参考以防我错过了一些细节,那就是我使用Wait()的功能:
// End frame drawing
void EndFrame(void)
{
SwapBuffers(); // Copy back buffer to front buffer
PollInputEvents(); // Poll user events
// Frame time control system
currentTime = GetTime();
drawTime = currentTime - previousTime;
previousTime = currentTime;
frameTime = updateTime + drawTime;
// Wait for some milliseconds...
if (frameTime < targetTime)
{
Wait((targetTime - frameTime)*1000.0f);
currentTime = GetTime();
double extraTime = currentTime - previousTime;
previousTime = currentTime;
frameTime += extraTime;
}
}