首先,我发现了很多关于这个主题的信息,但不幸的是没有解决这个问题的解决方案。
我只是想调节我的 C++ 程序以每秒 60 次迭代运行。我已经尝试了从 GetClockTicks() 到 GetLocalTime() 的所有方法来帮助调节,但每次我在 Windows Server 2008 机器上运行程序时,它的运行速度都比在本地机器上慢,我不知道为什么!
我知道基于“时钟”的函数调用会返回执行时花费的 CPU 时间,所以我去了 GetLocalTime,然后尝试区分开始时间和停止时间,然后调用 Sleep((FPS / 1000) - millisecondExecutionTime)
我的本地机器比服务器 CPU 快得多,所以很明显,我的想法是它正在关闭 CPU 滴答声,但这并不能解释为什么 GetLocalTime 不起作用。我一直基于http://www.lazyfoo.net/SDL_tutorials/lesson14/index.php更改 get_ticks() 并始终返回我可以在网络上找到的函数的这种方法。
例如采取以下代码:
#include <Windows.h>
#include <time.h>
#include <string>
#include <iostream>
using namespace std;
int main() {
int tFps = 60;
int counter = 0;
SYSTEMTIME gStart, gEnd, start_time, end_time;
GetLocalTime( &gStart );
bool done = false;
while(!done) {
GetLocalTime( &start_time );
Sleep(10);
counter++;
GetLocalTime( &end_time );
int startTimeMilli = (start_time.wSecond * 1000 + start_time.wMilliseconds);
int endTimeMilli = (end_time.wSecond * 1000 + end_time.wMilliseconds);
int time_to_sleep = (1000 / tFps) - (endTimeMilli - startTimeMilli);
if (counter > 240)
done = true;
if (time_to_sleep > 0)
Sleep(time_to_sleep);
}
GetLocalTime( &gEnd );
cout << "Total Time: " << (gEnd.wSecond*1000 + gEnd.wMilliseconds) - (gStart.wSecond*1000 + gStart.wMilliseconds) << endl;
cin.get();
}
对于此代码片段,在我的计算机 (3.06 GHz) 上运行,总时间 (ms) 为 3856,而在我的服务器 (2.53 GHz) 上,我得到 6256。因此它可能是处理器的速度,尽管比率为 2.53 /3.06 仅为 0.826797386,而 3856/6271 为 0.614893956。
我不知道睡眠功能是否正在做一些与预期完全不同的事情,尽管我不明白为什么会这样做,或者它是否是我获取时间的方法(即使它应该是世界时间(毫秒)而不是时钟周期时间。任何帮助将不胜感激,谢谢。