Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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.

Thanks

like image 231
Scott Davies Avatar asked Feb 24 '10 20:02

Scott Davies


People also ask

How do you convert ticks to milliseconds?

A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond (see TicksPerMillisecond) and 10 million ticks in a second.

What is tick Stopwatch?

A tick is the smallest unit of time that the Stopwatch timer can measure. Use the Frequency field to convert the ElapsedTicks value into a number of seconds.

Can you get 0 milliseconds on a Stopwatch?

Since each operation is averaging 500/1000000 = 0.00005 ms, the ticks of the stopwatch will accumulate some small value, but the ElapsedMilliseconds (or Milliseconds of the TimeSpan) will still be 0.

What is between millisecond and nanosecond?

Nanosecond is one billionth of a second. Microsecond is one millionth of a second. Millisecond is one thousandth of a second. Centisecond is one hundredth of a second.


2 Answers

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 stopwatch.Start();  // Do something for (int i = 0; i < 1000; i++) {     Thread.Sleep(1); }  // Stop timing stopwatch.Stop();  // 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); 

Output:

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

Note that stopwatch.ElapsedMilliseconds returns a long and is thus only precise up to the millisecond, while stopwatch.Elapsed.TotalMilliseconds returns a double and has the same precision as stopwatch.ElapsedTicks, except it's easier to use. ILSpy shows that TimeSpan.TotalMilliseconds is computed using ticks anyway.

like image 75
D'Arcy Rittich Avatar answered Sep 21 '22 01:09

D'Arcy Rittich


According to MSDN, Frequency tells you the number of ticks per second. Therefore:

Stopwatch sw = new Stopwatch(); // ... double ticks = sw.ElapsedTicks; double seconds = ticks / Stopwatch.Frequency; double milliseconds = (ticks / Stopwatch.Frequency) * 1000; double nanoseconds = (ticks / Stopwatch.Frequency) * 1000000000; 
like image 22
Zach Johnson Avatar answered Sep 21 '22 01:09

Zach Johnson