While developing a program to calculate the frequency and pulse width of the pulse generated by a 555 timer IC, coming to the PC via PC Parallel port. I noticed that every time I run the code it shows different values, so I start testing the Loops and timers for there accuracy. I have run the following code and come to the point that they are inaccurate (I might be wrong, please correct me, if I am!):
For Timers:
int sec = 0;
private void button2_Click(object sender, EventArgs e)
{
sec = DateTime.Now.Second;
i = 0;
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (sec == DateTime.Now.Second)
{
i++;
}
else
{
timer1.Enabled = false;
MessageBox.Show(i.ToString(),"Timer Output");
}
}
OUTPUT:
Should be same, but:
For LOOP:
private void button1_Click(object sender, EventArgs e)
{
i = 0;
CheckForIllegalCrossThreadCalls = false;
Thread t1 = new Thread(LoopTest);
t1.Start();
}
void LoopTest()
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
this.Cursor = Cursors.WaitCursor;
while (true)
{
if (sw.ElapsedMilliseconds != 1000)
{
i++;
}
else
{
break;
}
}
sw.Stop();
this.Cursor = Cursors.Default;
MessageBox.Show(i.ToString(), "Loop Output");
}
OUTPUT:
Should be same, but:
What should I do to make loops and timer accurate, Is there any way to do it? Or I have to go to hard and complex C code and DOS?
I think it is the basic reason for getting me wrong values in this question: Count Parallel port input frequency - C#
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…