views:

272

answers:

3

Related to my previous question, but with C#, I need the precise system time including milliseconds.

C# time function has accuracy up to 10 to 15 milliseconds, but not exactly 1 millisecond.

The same is the case with Queue performance counter. Is there any other way to get accuracy up to exact millisecond?

+3  A: 

Try System.Diagnostics.Stopwatch for high-resolution timing.

If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time.

Try the native DateTime.Ticks for system time accuracy up to one hundred nanoseconds; 1 millisecond = 10000 ticks.

while (true)
{
    System.Threading.Thread.Sleep(1);

    Console.WriteLine("{0} {1}",
        System.DateTime.Now.Ticks,
        System.DateTime.Now.ToString("ss:fff"));
}

PS > .\test.exe
    634134152924322129 52:432
    634134152924332129 52:433
    634134152924342130 52:434
    634134152924352130 52:435
    634134152924362131 52:436
    634134152924372131 52:437
    634134152924382132 52:438
    634134152924392133 52:439
    634134152924402133 52:440
    634134152924412134 52:441
    634134152924422134 52:442
    634134152924432135 52:443
xcud
He asked for the system time. The Stopwatch just gives an elapsed time.
Gabe
Calling `DateTime.Ticks` is no more accurate than `DateTime.Millisecond`. Internally, `DateTime.Millisecond` calls `DateTime.Ticks`
Dan Herbert
Right. I was just pointing out that according to MSDN and this rough test that it is accurate to at least the millisecond resolution that the questioner is asking for; hence the side by side Console.Output of DateTime as a string alongside Ticks.
xcud
+1  A: 

Windows does not want to waste electricity by updating the system clock 1000 times per second, so the default is to only update it 60-100 times per second. If you set the multimedia timer to 1ms, you can get 1ms resolution from the clock, but that's not recommended.

To elaborate more on the electricity savings, what happens when the CPU is idle for a period of time is that it can go into a very-low-power state. Whenever it gets interrupted (e.g. to increment the clock ticks) it has to leave its very-low-power state and use lots of electricity to power the whole CPU to service that interrupt. In other words, the additional power isn't in incrementing the clock ticks, it's in keeping the CPU awake to do it.

Since my laptop uses 10W at idle when the clock frequency is 60Hz and 11W when it's 1000Hz, and I get 300 minutes of battery life, that slower clock is giving me almost 30 extra minutes of battery life!

Gabe
Are you talking about the kernel interrupts? http://lwn.net/Articles/145973/
Nitrodist
Nitrodist: Yes, that's an explanation of the same problem.
Gabe
+1  A: 

You could use this DateTimePrecise class to get a high accuracy time in .NET

Dan Herbert