private long MinimumDelay() { TicksStopWatch watch = new TicksStopWatch(); TicksTiming timing = new TicksTiming(); watch.Start(); for (int i = 0; i < AdjustmentIterations; i++) { timing.WaitTicks(0); } watch.Stop(); return(watch.Elapsed() / AdjustmentIterations); }
private void AdjustDelay(Delays delays, int index) { TicksStopWatch watch = new TicksStopWatch(); TicksTiming timing = new TicksTiming(); long difference; long differencePerIteration; long average = 0; long oldAverage = 0; long delay = delays.values[index]; long adjustedDelay = delay; int adjustmentRuns = 1; long targetRuntime = AdjustmentIterations * delay; long minimumDelay = MinimumDelay(); WarmUpIterations(delay, timing); do { watch.Start(); for (int i = 0; i < AdjustmentIterations; i++) { timing.WaitTicks(adjustedDelay); } watch.Stop(); difference = targetRuntime - watch.Elapsed(); differencePerIteration = difference / AdjustmentIterations; if (-differencePerIteration > adjustedDelay) { adjustedDelay /= 2; } else { adjustedDelay += differencePerIteration; oldAverage = average; if (adjustmentRuns == 1) { average = adjustedDelay; } else { average = ((average * (adjustmentRuns - 1)) / adjustmentRuns) + (adjustedDelay / adjustmentRuns); } adjustmentRuns++; } if (adjustedDelay <= 0) { break; } if ((Math.Abs(average - oldAverage) < (0.01 * delay)) && adjustmentRuns > 10) { break; } }while (true); if (average < minimumDelay) { Sharpen.Runtime.Err.WriteLine(">> Smallest achievable delay: " + minimumDelay); Sharpen.Runtime.Err.WriteLine(">> Required delay setting: " + average); Sharpen.Runtime.Err.WriteLine(">> Using delay(0) to wait as short as possible."); Sharpen.Runtime.Err.WriteLine(">> Results will not be accurate."); average = 0; } delays.values[index] = average; }