1

I have an object which can be called MyResponse.

{
"TimeStampA": "2022-01-01 08:00:00.000",
"TimeStampB": "2022-01-01 08:00:00.100"
}

The response is created by a service A (which set TimeStampA property) and then forwarded to service B (which set TimeStampB property). Service A and service B are running on the same server.

TimeStampA and TimeStampB are both set using DateTime.Now function.

Problem : when the frequency of MyResponse publication is very high, i can see that in some cases, TimeStampB < TimeStampA

I found this article telling that DateTime.Now can return the same value if called repeatedly in a short time interval. https://learn.microsoft.com/en-us/dotnet/api/system.datetime.now?redirectedfrom=MSDN&view=net-7.0#System_DateTime_Now It seems to explain why TimeStampB < TimeStampA in some cases ?

So, how to set the timestamp with precision ? Stopwatch seems more appropriate for durations, but the items are manipulated in 2 services.

My goal is to calculate the duration between TimeStampA and TimeStampB

Thanks

Abbas Aryanpour
  • 391
  • 3
  • 15
  • 2
    I find it strange still that B is strictly less than A, while being called later. The same would be no surprise, but why less? – Evk Dec 29 '22 at 18:11
  • 1
    How do you store and compare the timestamps? Ad DateTime, as string? – NineBerry Dec 29 '22 at 18:13
  • It is technically possible. The clock gets updated by the OS clock interrupt handler, it ticks 64 times per second by default. Recent versions of Windows allow that default to be changed and limit the affect to a specific process. Documented in the article for timeBeginPeriod(). In general, differences of 16 msec or less should be ignored. – Hans Passant Dec 29 '22 at 18:22
  • What precision are you aiming for? Even if we rule out the "overtaking" problem, maybe `DateTime.Now` may be not sufficiently accurate for what you want to achieve? – Fildor Dec 29 '22 at 18:59
  • Timestamps are store as datetimes. Sometimes, TimeStampB is 5-10ms earlier than TimeStampA. Ideally I'm looking for 1ms precision. – CasqueOuille Dec 30 '22 at 09:11
  • What happens to those dates between that DateTime.Now assignment and the comparison? Could they possibly go through JSON or XML where they could lose fractions of a second? – Hans Kesting Dec 31 '22 at 10:37

0 Answers0