Skip to content

Instantly share code, notes, and snippets.

@slembcke
Last active June 18, 2023 19:05
Show Gist options
  • Save slembcke/b2ff9427472eee36caa01fafcbf5773a to your computer and use it in GitHub Desktop.
Save slembcke/b2ff9427472eee36caa01fafcbf5773a to your computer and use it in GitHub Desktop.
Filter frame timing to try and remove scheduler jitter.
double delta_time_filtered(double dt_nanos){
// Warm start the filter by assuming 60 Hz.
static double x[] = {1.6e7, 1.6e7, 1.6e7}, y[] = {1.6e7, 1.6e7, 1.6e7};
// IIR filter coefficients. 2rd order lowpass butterworth at 1/128 the sample rate.
static const double b[] = {6.321391700454014e-5, 0.00012642783400908025, 6.321391700454014e-5};
static const double a[] = {1.0, -1.9681971279272976, 0.9684499835953156};
// Apply IIR filter coefficients.
double value = b[0]*dt_nanos;
for(uint i = 2; i > 0; i--){
x[i] = x[i - 1]; y[i] = y[i - 1];
value += b[i]*x[i] - a[i]*y[i];
}
x[0] = dt_nanos; y[0] = value;
// Quantize the delta time, truncating towards the filtered value.
return trunc(dt_nanos/value - 1)*value + value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment