Wednesday, June 16, 2010

C# - Timer Precision Issue

Timer precision issue doesn't only affect Java, it should affect most programming language. It is because when you pause a thread, it gives away its right and allow the OS to schedule their job.

Thus, Thead.Sleep/Monitor.Wait does not guarantee the sleep time.

To archive high resolution, you can try using multimedia timer such as QueryPerformanceCounter . This is good for perform elapse calculations.

Or you can use timeBeginPeriod to requests a minimum resolution for periodic timers.

For example, to reduce the resolution to 1 ms

[DllImport("winmm.dll")]
internal static extern uint timeBeginPeriod(uint period);
[DllImport("winmm.dll")]
internal static extern uint timeEndPeriod(uint period);

timeBeginPeriod(1);
while(true)
{
Thread.Sleep(1); // will sleep 1ms every time
}
timeEndPeriod(1);


No comments:

Post a Comment

Hadoop - How to setup a Hadoop Cluster

Below is a step-by-step guide which I had used to setup a Hadoop Cluster Scenario 3 VMs involved: 1) NameNode, ResourceManager - Host...