Answered by:
Divided by zero error
Question

Hi,
I've got "Divided by zero error" to last 2 lines below. What to adjust?
if (Stopwatch.Frequency > 0) { long microseconds = sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L)); long nanoseconds = sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L * 1000L));
Many Thanks & Best Regards, Hua Min
Answers

Observe that Stopwatch.Frequency is a long, and your 1000L constants are also longs. This causes the compiler to generate a division of type long, i.e., it will not have any decimal places. Therefore, if the result is less than 1 it will be rounded to zero.
For example, if the Frequency is less than 1000000, then (Stopwatch.Frequency / (1000L * 1000L)) will be zero. Subsequently, when computing sw.ElapsedTicks divided by the preceding value, you get a division by zero.
One easy solution is to change the order in which the operations are done by moving around the parentheses:
long microseconds = (sw.ElapsedTicks* (1000L * 1000L)) / Stopwatch.Frequency;
Of course, you can now get an overflow if the product is too large. At this point, you may consider switching over to floatingpoint arithmetic.
 Proposed as answer by Ante Meridian Tuesday, February 12, 2019 10:18 PM
 Marked as answer by Jackson_1990 Wednesday, February 13, 2019 7:53 AM
All replies

Consider the elapsed time example from the documentation at https://docs.microsoft.com/enus/windows/desktop/SysInfo/acquiringhighresolutiontimestamps#examplesforacquiringtimestamps
using System.Diagnostics;
long StartingTime = Stopwatch.GetTimestamp();
// Activity to be timed
long EndingTime = Stopwatch.GetTimestamp();
long ElapsedTime = EndingTime  StartingTime;
double ElapsedSeconds = ElapsedTime * (1.0 / Stopwatch.Frequency); Edited by RLWA32 Tuesday, February 12, 2019 10:39 AM

Observe that Stopwatch.Frequency is a long, and your 1000L constants are also longs. This causes the compiler to generate a division of type long, i.e., it will not have any decimal places. Therefore, if the result is less than 1 it will be rounded to zero.
For example, if the Frequency is less than 1000000, then (Stopwatch.Frequency / (1000L * 1000L)) will be zero. Subsequently, when computing sw.ElapsedTicks divided by the preceding value, you get a division by zero.
One easy solution is to change the order in which the operations are done by moving around the parentheses:
long microseconds = (sw.ElapsedTicks* (1000L * 1000L)) / Stopwatch.Frequency;
Of course, you can now get an overflow if the product is too large. At this point, you may consider switching over to floatingpoint arithmetic.
 Proposed as answer by Ante Meridian Tuesday, February 12, 2019 10:18 PM
 Marked as answer by Jackson_1990 Wednesday, February 13, 2019 7:53 AM