John John - 27 days ago 15
C# Question

Executing events at very fast, precise, and accurate rates

I'm making a program with a global mouse and keyboard hook. The program will record the user's input when they press a record button and will stop recording once they press a stop button. I'm getting the timespan of each event by using a stopwatch, as that seems to be the most accurate method.

Here's a small snippet of the events a user's recording:

01:45:20 - Time: 00:00:03.7028259 - Mousemove
01:45:20 - Time: 00:00:03.7190386 - Mouseleftdown
01:45:20 - Time: 00:00:03.7363274 - Mousemove
01:45:20 - Time: 00:00:03.7431332 - Mousemove
01:45:20 - Time: 00:00:03.7519057 - Mousemove
01:45:20 - Time: 00:00:03.7594302 - Mouseleftup


As you can see, some events events are nearly 8 milliseconds apart (this seems to be the smallest amount of time I can get between each event).

The user can press the play button, and their recording will begin to play. At first, I looked into the
Timer
component as it seemed perfect for this situation. However, the component is fairly inaccurate, so I thought I'd ask here. I considered the idea of making a new thread with a stopwatch and a while loop that will compare the events TimeSpans and the stopwatch's Elapsed time, but that would suck up the CPU a lot. What would you guys do to replay the events accurately? Am I wasting my time looking for something so accurate on a desktop?

usr usr
Answer

Raise the timer resolution to 1ms (which is max). Then use any timing method you like (timers, sleep, events, ...) to obtain 1ms accuracy. 1000Hz should be enough for anything aimed at human perception.