7VoltCrayon
7VoltCrayon

Reputation: 662

C# High accuracy Timing

I am making a small typing test in C# in which the program asks you to type a word and then shows you your time. I was using the c# timer class (drag and drop a timer from the toolbox), with a Tick time of 1ms, however it wasn't giving me accurate results, so I substituted it for a StopWatch , so now the timing is super accurate, but the problem is that it seems that you cannot assign event handlers to a StopWatch so although I can show the user his time when he FINISHES the word, I cannot actually show hum the time WHILE he is typing. Thoughts?

Upvotes: 1

Views: 279

Answers (3)

Paul Sasik
Paul Sasik

Reputation: 81429

Use another Timer that fires events every 10th of a second or so and polls for the Stopwatch value. It won't be nearly as accurate as the Stopwatch since there will be a lag but humans can't really react to anything faster than a 10th of a second.

Upvotes: 3

foxy
foxy

Reputation: 7672

Use the System.Timers.Stopwatch class, and check if high resolution is available by checking the field IsHighResolution (System.Timers.Stopwatch.IsHighResolution == true).

Then, whenever you need something fired, fire it through another timer at the lowest interval possible, which checks the value of your Stopwatch. Though this won't be perfect (you don't even need close to perfect), it'll work.

Upvotes: 2

driis
driis

Reputation: 164291

Use a StopWatch to accurately measure time; and use a Timer to periodically fire a UI update, displaying the time measured by the StopWatch. For UI, you don't need 1 ms resolution (The screen update time is likely to be larger than 1 ms, and, the human eye won't be able to perceive updates that fast anyways).

Try having updates each 40 - 100 ms, I think that will be adequate.

Upvotes: 4

Related Questions