Yesterday, a friend of mine called me. He is writing a small program for a client and this program should execute simple operations at a given time. These operations don't take very long, but there will be a lot of checks in a second to make sure that the operation starts (nearly) exactly at the given time.
My friend has concerns that a simple "TriggerDate>DateTime.UtcNow" would take to long so he started to use Environment.Ticks. The Ticks operation is for sure faster, because this is only a simple addition and comparsion. However, the ticks will go from Int.MinValue to Int.MaxValue in about 49 days, when the counter will flip back to Int.MinValue. This caused him a lot of headache.
I first tried to improve his code, when I realized I first need to determine how much slower is a DateTime comparison. So I wrote the following small test code:
private void CheckDateTime()
{
DateTime dtStart = dtNow new TimeSpan(0, 0, 5);
long iCount = 0;
DateTime dtNow = DateTime.UtcNow;
for (; DateTime.UtcNow < dtStart; iCount )
{
}
PrintResult(dtNow, iCount);
}
private void CheckTicks()
{
int iTick = Environment.TickCount & int.MaxValue;
int iTickStart = iTick (5 * 1000);
long iCount = 0;
DateTime dtNow = DateTime.UtcNow;
for (; (Environment.TickCount & int.MaxValue) < iTickStart; iCount )
{
}
PrintResult(dtNow, iCount);
}
private void PrintResult(DateTime starttime, long Operations)
{
DateTime dtNewNow = DateTime.UtcNow;
TimeSpan elapsed = starttime - dtNewNow;
textBox1.Text = "Time: " elapsed.TotalSeconds.ToString() "\r\n";
textBox1.Text = "Operations: " Operations.ToString() "\r\n";
}
The result: On a standard 1.8 GHz Intel Core 2 machine (E2160), I had 192 million DateTime comparisons in about 5 seconds and 593 million TickCount comparisons. This means: My computer is able to do a whopping 39 millions DateTime comparisons/second and 120 million TickCount comparisons/second.
Conclusion: Yes, DateTime is slower than checking Ticks, but given these figures you really don't need to care about this difference.
No comments:
Post a Comment