Rorrik
Rorrik

Reputation: 370

How time consuming is TImeSpan arithmetic compared to normal arithmetic?

I have a C# program with an interrupt that processes part of a list I'd like to have run as often as every 40 ms, but the math inside the interrupt can freeze up the program for lists with certain sizes and properties.

I'm tempted to try speeding it by removing the TimeSpan adds and subtracts from the math and converting them all to TotalMilliseconds before performing the arithmetic rather than after. Does anyone know what the overhead is on adding and subtracting TimeSpans compared to geting the TotalMilliseconds and adding and subtracting that?

Thanks.

Upvotes: 1

Views: 665

Answers (1)

Hans Passant
Hans Passant

Reputation: 941555

That would be unwise, Timespan.TotalMilliseconds is a property of type double with a unit of one millisecond. Which is highly unrelated to the underlying structure value, Ticks is a property getter for the underlying field of type long with a unit of 100 nanoseconds. The TotalMilliseconds property getter goes through some gymnastics to convert the long to a double, it makes sure that converting back and forth produces the same number.

Which is a problem for TimeSpan, it can cover 10,000 years with a precision of 100 nanoseconds. A double however has 15 significant digits, that's not enough to cover that many years with that kind of precision. The TotalMilliseconds property performs rounding, not just conversion, it makes sure the returned value is accurate to one millisecond. Not 100 nanoseconds. So converting it back and forth always produces the same value.

Which does work: 10,000 years x 365.4 days x 24 hours x 60 minutes x 60 seconds x 1000 milliseconds = 315,705,600,000,000 milliseconds. Count the digits, exactly 15 so exactly good enough to store in a double without loss of accuracy. Happy coincidence, isn't it?

Answering the question: if you care about speed then always use Ticks, never TotalMilliseconds. That's a very fast 64-bit integer operation. Way faster than an integer-to-float + rounding conversion.

Upvotes: 11

Related Questions