Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Ticks does NOT have a resolution af 100 ns? [duplicate]

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 - 634940160118679615

867 - 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?

like image 621
Jesper R. Hansen Avatar asked Jan 17 '13 10:01

Jesper R. Hansen


People also ask

What is DateTime ticks in C#?

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.

How accurate is DateTime now in C#?

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 .

How many ticks are in a second C#?

Ticks are 100 nanoseconds long, so there are 10,000,000 of them per second.

What is ticks in timespan?

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.


1 Answers

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.

like image 70
Matthew Watson Avatar answered Sep 30 '22 13:09

Matthew Watson