I am trying to build an application that does not have to be super performant in general, except for the timestamp of a keyboard press (or external controller button press). I would like the timestamp to be as precise as possible, preferably down to +/- 5ms. This is for a scientific application. What is the best programming paradigm to achieve this with minimal latency? Which of the following is preferable?
(a) Create a worker thread that runs in a higher priority and loops to see if a key was pressed. Use Sleep(x)
where x
is less than 5.
(b) Create an keyboard hook, which has an asynchronous callback.
(c) Another option.
In addition to an answer, any code (or link to sample) would be much appreciated since I am a reasonably new dev.
EDIT: Nomenclature. Should have been more careful. By timestamp, I mean time in general, not necessarily the full Day Month Year Hour Minute Second Millisecond. I was planning on using the StopWatch class from the beginning, because all I need is the time between the start of an event in the program and the time of the button press. Sorry if this was not clear.
From comments:
I am looking for the difference between the start of an event and the key press.
It's important to understand that that's very different to trying to get the actual timestamp of a key press.
This situation is exactly what Stopwatch
is for. Yes, use that and be grateful you're not really trying to get a timestamp.
Just use Stopwatch.StartNew
when the event starts, and Stopwatch.Stop
on the key press event. There's the slight latency of the event handler firing, but that will be tiny compared with anything else - I'd be astonished if it caused you any problems here.
See more on this question at Stackoverflow