Search code examples
c#timestopwatch

Stopwatch Recording to 4 decimal places


I am using the system diagnostics stopwatch to time how long my function takes to run. Currently the output is 0 as it is under 1ms. How can I record to under a millisecond to 4 decimal places?. I am aware of 'ticks', however I would prefer not to convert ticks to milliseconds for all my timings.

I am currently using the below code:

System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Start();
myFunction();
watch.Stop();
double elapsedTime = watch.ElapsedMilliseconds;   //How to get to 4 decimal places? 
Console.WriteLine("Time " + elapsedTime );

Solution

  • Instead of milliseconds you should work on watch.Elapsed.TotalMilliseconds.

    Stopwatch watch = new Stopwatch();
    watch.Start();
    myFunction();
    watch.Stop();
    double elapsedTime = watch.Elapsed.TotalMilliseconds;
    Console.WriteLine("Time " + elapsedTime);
    

    enter image description here

    Output enter image description here