Scott Davies Scott Davies - 4 months ago 68
C# Question

How do you convert Stopwatch ticks to nanoseconds, milliseconds and seconds?

This is a very basic question...quite embarassing, but here goes:

I have a Stopwatch block in C# code. I determine the elapsed time in ticks and then want to convert to ns, ms, s. I know that the Frequency is provided by the Stopwatch class and that it is required for conversion.



Stopwatch.Elapsed is a TimeSpan, so you can do myStopwatch.Elapsed.TotalMilliseconds, myStopwatch.Elapsed.TotalSeconds, etc.

// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();

// Begin timing

// Do something
for (int i = 0; i < 1000; i++)

// Stop timing

// Write result
Console.WriteLine("Time elapsed (s): {0}", stopwatch.Elapsed.TotalSeconds);
Console.WriteLine("Time elapsed (ms): {0}", stopwatch.Elapsed.TotalMilliseconds);
Console.WriteLine("Time elapsed (ns): {0}", stopwatch.Elapsed.TotalMilliseconds * 1000000);


Time elapsed (s): 2.4976622
Time elapsed (ms): 2497.6622
Time elapsed (ns): 2497662200