Possible Duplicate:
C# DateTime.Now precision
There are a few questions on SO regarding high-resolution timing in .NET where it is stated (as in the MSDN documentation) that the DateTime.Ticks has a resulution of 100 nano-seconds.
But this seem not to be the case at all in real-life. If I run the code below, I would expect it to generate lines, where the Tick value varies for each line, where a lot of lines are with the the same Milisecond value. But it doesn't - the ticks value stays the same until next shift in milisecond value, adding nothing to the resolution of the time-stamp.
private static List<string> GetTimeLine(long iterations)
{
List<string> liste = new List<string>();
for (long i = 0; i <= iterations; i++)
{
liste.Add(DateTime.Now.Millisecond.ToString() + " - " + DateTime.Now.Ticks.ToString());
}
return liste;
}
static void Main(string[] args)
{
Console.WriteLine("Generating timeline");
guids = GetTimeLine(10000);
File.WriteAllLines(@"C:\Test\GUIDS.TXT", guids);
Console.WriteLine("File written - Press ENTER");
Console.ReadLine();
}
Example of result output:
...
867 - 634940160118679615867 - 634940160118679615
867 - 634940160118679615
867 - 634940160118679615
867 - 634940160118679615
868 - 634940160118689616
868 - 634940160118689616
868 - 634940160118689616
...
So what is the method for getting more than miliseconds resolution in .NET?
If the DateTime object has its Kind property set to Unspecified , its ticks represent the time elapsed time since 12:00:00 midnight, January 1, 0001 in the unknown time zone. In general, the ticks represent the time according to the time zone specified by the Kind property.
From MSDN you'll find that DateTime. Now has an approximate resolution of 10 milliseconds on all NT operating systems. The actual precision is hardware dependent. Better precision can be obtained using QueryPerformanceCounter .
Ticks are 100 nanoseconds long, so there are 10,000,000 of them per second.
The smallest unit of time is the tick, which is equal to 100 nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond.
The most accurate way of measuring elapsed time in C# is to use the Stopwatch class.
This uses the microprocessor's performance counter, implemented with calls to QueryPerformanceCounter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With