I have a program written in C#, VS 2005. It has a feature of recording data and timestamp. I need millisecond level time resolution because the data sampling cycle time maybe 50ms or less. I used DateTime.Now.Millisecond to retrieve system time, but I found on some computers, the actual intervals between two timestamps are not 50ms but 62-63ms.
So I simplified my code and tried on several computers, here is the code:
static void Main(string[] args)
{
while (true)
{
Thread.Sleep(50);
Console.WriteLine("{0}", DateTime.Now.Millisecond);
}
}
Here is the result on Win7 SP1:
928 991 53 116 178 240 306 368 431 493 555 618 ...
Note that the interval is about 62-63ms.
I know that Windows NT series OS time resolution is about 16ms so I'm not very surprised about the result.
BUT, the question is that when I test the same program on some other Win7(SP1) computers, the result is accurate and the intervals are almost always 50ms, I don't know why the behavior differs so much.
So, my question are:
- How to explain these results?
- How could I get accurate millisecond level timestamp? Is it possible(on Win7)?
BTW,
1) I test it on Win10, the interval is about 50-51ms.
2) I tried using Stopwatch, it has no effect.
3) Environment.TickCount is not accurate too.
4) I tried using VS 2015, the same result.
========================================
here is my new test code:
static void Main(string[] args)
{
long ticks = DateTime.Now.Ticks;
int tEV = Environment.TickCount;
while (true)
{
Thread.Sleep(50);
Console.WriteLine("{0}, {1}, {2}",
DateTime.Now.Ticks - ticks,
DateTime.Now.Millisecond,
Environment.TickCount - tEV);
ticks = DateTime.Now.Ticks;
tEV = Environment.TickCount;
}
}
Here is the output result, we can see the second column (DateTime.Now.Millisecond), the interval is exactly 50 msec while the last column(TickCount) varies.
510000, 547, 47
500000, 597, 62
500000, 647, 47
500000, 697, 47
500000, 747, 46
500000, 797, 47
500000, 847, 63
500000, 897, 46
500000, 947, 47
500000, 997, 47
500000, 47, 47
500000, 97, 62
500000, 147, 47
500000, 197, 47
500000, 247, 47
500000, 297, 46
500000, 347, 63
500000, 397, 47
500000, 447, 46
500000, 497, 47
500000, 547, 47
500000, 597, 62
500000, 647, 47
500000, 697, 47
500000, 747, 47
500000, 797, 62
500000, 847, 47
500000, 897, 47
500000, 947, 47
500000, 997, 46
500000, 47, 63