From 9bf912fd898d0133d68105f16739740b47230ba7 Mon Sep 17 00:00:00 2001 From: Mattrixwv Date: Sun, 23 Aug 2020 04:32:19 -0400 Subject: [PATCH] Updated to be more reliable if tick freq changes --- CSClasses/Stopwatch.cs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/CSClasses/Stopwatch.cs b/CSClasses/Stopwatch.cs index f0a5249..66b34d2 100644 --- a/CSClasses/Stopwatch.cs +++ b/CSClasses/Stopwatch.cs @@ -25,6 +25,7 @@ namespace mee{ private System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); //The stopwatch that is used private enum TIME_RESOLUTION{ NANOSECOND, MICROSECOND, MILLISECOND, SECOND, MINUTE, HOUR, ERROR }; private const int NUM_TO_RUN = 100000; + private readonly long nanosecPerTick = 1000000000L / System.Diagnostics.Stopwatch.Frequency; //Functions //Constructor makes sure all values are set to defaults public Stopwatch(){ @@ -47,28 +48,27 @@ namespace mee{ } //Returns the timer in nanoseconds public decimal getNano(){ - //Each tick = 100 nanoseconds - return (decimal)stopwatch.ElapsedTicks * 100m; + return (decimal)nanosecPerTick * (decimal)stopwatch.ElapsedTicks; } //Returns the timer in microseconds public decimal getMicro(){ - return (decimal)stopwatch.ElapsedTicks / 10m; + return getNano() / 1000m; } //Returns the timer in milliseconds public decimal getMilli(){ - return (decimal)stopwatch.ElapsedTicks / 10000m; + return getNano() / 1000000m; } //Returns the timer in seconds public decimal getSecond(){ - return (decimal)stopwatch.ElapsedTicks / 10000000m; + return getNano() / 1000000000m; } //Returns the timer in minutes public decimal getMinute(){ - return (decimal)stopwatch.ElapsedTicks / 600000000m; + return getNano() / 60000000000m; } //Returns the timer in hours public decimal getHour(){ - return (decimal)stopwatch.ElapsedTicks / 36000000000m; + return getNano() / 3600000000000m; } //Returns the timer as a string at the 'best' resolution. (Goal is xxx.xxx) public string getStr(){ @@ -80,7 +80,7 @@ namespace mee{ decimal duration = nanoseconds; //Reduce the number to the appropriate number of digits. (xxx.x) //This loop works down to seconds - TIME_RESOLUTION resolution = new TIME_RESOLUTION(); + TIME_RESOLUTION resolution; for(resolution = TIME_RESOLUTION.NANOSECOND;(resolution < TIME_RESOLUTION.SECOND) && (duration >= 1000);++resolution){ duration /= 1000; } @@ -99,7 +99,6 @@ namespace mee{ } //Turn the number into a string - //string time = string.Format("{0C3}", duration); string time = duration.ToString("C3").Substring(1); //Tack on the appropriate suffix for resolution