My requirements:
1. Generally smooth flow.
2. Try to smooth out bad frames ( bad frames == frames who have a long running time compared to other frames [ex: calculate big AI decision] ).
I find that most frames run in under a millisecond, but some frames take as much as 70ms.
Currently I am using a sliding window (Code below).
I wait until 2 seconds have elapsed since the last 60 frames have been calculated (I am using 30FPS).
Problems is, this algorithm is not as stable as I hoped. Every once in a while I have a long running logic frame, and it throws off the next frames. When it disappears from the sliding window, it causes another timing artefact.
Does anyone have a suggestion for a better FPS limiter? (not limiting graphics FPS, just the logic frames...)
Thinking of trying a simple low-pass filter of some-sort.
Solution does not have to be high-performance (this code only gets called when the CPU has time to rest)
public class FrequencyConstrainer {
double m_FPS;
Queue<Long> m_Ticks = new LinkedList<Long>();
public FrequencyConstrainer(double FPS) {
m_FPS = FPS;
}
public void setFPS(double FPS) {
m_FPS = FPS;
}
public void clear() {
m_Ticks.clear();
}
public void Tick() {
m_Ticks.add(System.currentTimeMillis());
while (m_Ticks.size() > m_FPS*2) {
m_Ticks.poll();
}
}
public long getNextExecutionTime() {
if (m_Ticks.isEmpty()) {
return System.currentTimeMillis();
} else {
return m_Ticks.peek() + (long) ((m_Ticks.size() * 1000) / m_FPS);
}
}
public void ConstrainExecutionSpeed() throws InterruptedException {
long targetTime = getNextExecutionTime();
while (System.currentTimeMillis() < targetTime) {
Thread.sleep(10);
}
}
}