Stopwatch that runs faster than 15ms
I currently have a timer that I assumed called a method defined on a field TimerCallback
every 5ms, but after reading the class Timer
and resolving it, I found that the class Timer
has a resolution of 15ms or more.
eg.
autoDispatchTimer = new Timer(new TimerCallback(this.SendData), null, 0, 5);
I also looked into the usage Stopwatch
as it allows for a higher resolution, but I'm still not sure how to use it Stopwatch
to accomplish the same operation. Is there anyway this can be done with an object Stopwatch
?
Will this be a case of reading a property ElapsedMilliseconds
and calling a method SendData
, or am I misunderstanding how it works Stopwatch
in C #?
Help with this request would be greatly appreciated.
EDIT: I fully understand that the timer has 15ms precision, so the rest of my question is asking for an alternative that is faster. The title has been changed to reflect this.
source to share
The problem is that it Timer
pauses in the background and at some point gets time to do something. This is guaranteed to be no faster than the time indicated on your timer (so it will take at least the indicated time, it may take longer). I usually get a few milliseconds before it returns. The timer is accurate to 15ms on Windows 7 and above , so there is no way to speed it up.
The only thing faster than Timer
is the loop while
. You can use that or rethink your design (at least that's what I will be doing).
source to share
Timer resolution documentation says:
The system timer resolution determines how often Windows performs two main actions:
- Refresh the timer mark if a full tick expires.
- Check if the scheduled timer object has expired.
Tick ββtimer is an elapsed time concept that Windows uses to keep track of the time of day and quantum times of a thread. By default, the clock interrupt and timer are the same, but Windows or an application can change the clock interrupt period.
The default timer resolution on Windows 7 is 15.6 milliseconds (ms). Some apps reduce this to 1ms, which will reduce battery life on mobiles by up to 25 percent.
However, you can try the following:
[DllImport("ntdll.dll", EntryPoint = "NtSetTimerResolution")]
public static extern void NtSetTimerResolution(uint DesiredResolution, bool SetResolution, ref uint CurrentResolution);
private void Foo()
{
uint DesiredResolution = 9000;
bool SetResolution= true;
uint CurrentResolution = 0;
NtSetTimerResolution(DesiredResolution, SetResolution, ref CurrentResolution);
}
You can also refer to High Performance Timer in C #
source to share