Search code examples
vbaexceltimercellular-automata

Average time per step is constant despite a variable delay


I've made a cellular automaton (Langton's ant FYI) on VBA. At each step, there is a Sleep(delay) where delay is a variable. I've also added DoEvents at the end of a display function to ensure that each step is shown on screen. With a Timer I can monitor how long one step require in average. The result is plotted on the graph bellow (Y-axis : Time per step (in ms). X-axis : delay (in ms))

Time per step (in ms) vs <code>delay</code>

Could you explain to me why it looks like that? Especially why does it remain steady ? Because IMO, I'm suppose to have (more or less) a a straight line. I got these results whitout doing anything else on my computer during the whole process.

Thank you in advance for your help,


Solution

  • That would be because the Sleep API is based off of the system clock. If the resolution of your clock is lower than the time you are sleeping, then it will round up to the nearest resolution of your system clock. You may be able to call timeGetDevCaps to see the minimum timer resolution of your system.

    Think about it this way. You have a normal watch that only includes your usual Hour/Minute/Second hand (no hands for 1/1000, etc). You are wanting to time half a second, but your watch only moves in 1 second intervals - hence your watch's resolution is 1 tick per second. You would not know that half a second has actually passed by until the full second passes by due to this resolution, so it's rounded to the next tick.