Is there a high resolution (microsecond, nanosecond) DateTime object available for the CLR?

前端 未结 6 1335
情深已故
情深已故 2020-12-08 05:02

I have an instrument that stores timestamps the microsecond level, and I need to store those timestamps as part of collecting information from the instrument. Note that I do

6条回答
  •  攒了一身酷
    2020-12-08 05:34

    If I really needed more accuracy than the 100 ns resolution provided by DateTime, I would consider creating a structure that contains a DateTime and an integer value:

    public struct HiResDateTime
    {
        public HiResDateTime(DateTime dateTime, int nanoseconds)
        {
            if (nanoSeconds < 0 || nanoSeconds > 99) 
                throw new ArgumentOutOfRangeException(...);
            DateTime = dateTime;
            Nanoseconds = nanoseconds;
        }
    
        ... possibly other constructors including one that takes a timestamp parameter
        ... in the format provided by the instruments.
    
        public DateTime DateTime { get; private set; }
        public int Nanoseconds { get; private set; }
    
        ... implementation ...
    }
    

    Then implement whatever is needed, for example:

    • Comparison (DateTime first, then Nanoseconds)
    • ToString() e.g. format DateTime to 100 ns accuracy then append nanoseconds.
    • Conversion to/from DateTime
    • Add/subtract (might need a similar HiResTimeSpan) ... etc. ...

提交回复
热议问题