문제

나는 일상적으로 동작 날짜/시간입니다.UtcNow 을 하고 있는 동안 일부 단위 테스트를 확인할 수 있습니다그것은 나타나는 경우 호출됩니다.지금/UtcNow 연속해서,그것은 당신에 대해 같은 값 이상이 예상보다는 시간 간격을 보다 더 정확하게 캡처 밀리초 단위로.

내가 알고 있는 클래스 스톱워치는 것이 더 적합하고 정확한 시간을 측정하지만,많은 관심을 갖게 되었다면 누군가를 설명할 수 있는 이 동작에서 DateTime?은 거기에 공식적인 문서화된 정밀도를 위해 날짜/시간입니다.지금(예를 들어,정확한 위 이내에 50ms?)?왜 날짜/시간입니다.지금 만든 것 보다 정확히 무엇 대부분의 CPU 클럭 수 있을 처리하는가?어쩌면 그것은 단지 설계에 대한 공통 분모 CPU?

public static void Main(string[] args)
{
    var stopwatch = new Stopwatch();
    stopwatch.Start();
    for (int i=0; i<1000; i++)
    {
        var now = DateTime.Now;
        Console.WriteLine(string.Format(
            "Ticks: {0}\tMilliseconds: {1}", now.Ticks, now.Millisecond));
    }

    stopwatch.Stop();
    Console.WriteLine("Stopwatch.ElapsedMilliseconds: {0}",
        stopwatch.ElapsedMilliseconds);

    Console.ReadLine();
}
도움이 되었습니까?

해결책

Why would DateTime.Now be made less precise than what most CPU clocks could handle?

A good clock should be both precise and accurate; those are different. As the old joke goes, a stopped clock is exactly accurate twice a day, a clock a minute slow is never accurate at any time. But the clock a minute slow is always precise to the nearest minute, whereas a stopped clock has no useful precision at all.

Why should the DateTime be precise to, say a microsecond when it cannot possibly be accurate to the microsecond? Most people do not have any source for official time signals that are accurate to the microsecond. Therefore giving six digits after the decimal place of precision, the last five of which are garbage would be lying.

Remember, the purpose of DateTime is to represent a date and time. High-precision timings is not at all the purpose of DateTime; as you note, that's the purpose of StopWatch. The purpose of DateTime is to represent a date and time for purposes like displaying the current time to the user, computing the number of days until next Tuesday, and so on.

In short, "what time is it?" and "how long did that take?" are completely different questions; don't use a tool designed to answer one question to answer the other.

Thanks for the question; this will make a good blog article! :-)

다른 팁

DateTime 의 정밀도가 다소 시스템의 실행되고 있다.정밀도와 관련의 컨텍스트 스위치는 경향이 있다 약 15 16ms.(시스템에,그것은 실제로 14ms 내에서 테스트,하지만 내가 본 일부 노트북 컴퓨터는 그것이 가까이 35-40ms 정확도.)

베드로는 브롬베르크가 쓴 는 문서에는 고정밀 코드를 타이밍 C#에서는 설명이다.

I would like a precise Datetime.Now :), so I cooked this up:

public class PreciseDatetime
{
    // using DateTime.Now resulted in many many log events with the same timestamp.
    // use static variables in case there are many instances of this class in use in the same program
    // (that way they will all be in sync)
    private static readonly Stopwatch myStopwatch = new Stopwatch();
    private static System.DateTime myStopwatchStartTime;

    static PreciseDatetime()
    {
        Reset();

        try
        {
            // In case the system clock gets updated
            SystemEvents.TimeChanged += SystemEvents_TimeChanged;
        }
        catch (Exception)
        {                
        }
    }

    static void SystemEvents_TimeChanged(object sender, EventArgs e)
    {
        Reset();
    }

    // SystemEvents.TimeChanged can be slow to fire (3 secs), so allow forcing of reset
    static public void Reset()
    {
        myStopwatchStartTime = System.DateTime.Now;
        myStopwatch.Restart();
    }

    public System.DateTime Now { get { return myStopwatchStartTime.Add(myStopwatch.Elapsed); } }
}

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.

For what it's worth, short of actually checking the .NET source, Eric Lippert provided a comment on this SO question saying that DateTime is only accurate to approx 30 ms. The reasoning for not being nanosecond accurate, in his words, is that it "doesn't need to be."

From MSDN documentation:

The resolution of this property depends on the system timer.

They also claim that the approximate resolution on Windows NT 3.5 and later is 10 ms :)

The resolution of this property depends on the system timer, which depends on the underlying operating system. It tends to be between 0.5 and 15 milliseconds.

As a result, repeated calls to the Now property in a short time interval, such as in a loop, may return the same value.

MSDN Link

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top