Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopwatch vs. using System.DateTime.Now for timing events [duplicate]

I wanted to track the performance of my code so I stored the start and end time using System.DateTime.Now. I took the difference between the two as the time my code to execute.

I noticed though that the difference didn't appear to be accurate. So I tried using a Stopwatch object. This turned out to be much, much more accurate.

Can anyone tell me why Stopwatch would be more accurate than calculating the difference between a start and end time using System.DateTime.Now?

BTW, I'm not talking about a tenths of a percent. I get about a 15-20% difference.

like image 800
Randy Minder Avatar asked May 27 '10 17:05

Randy Minder


People also ask

How accurate is the stopwatch class C#?

Stopwatch class does accurately measure time elapsed, but the way that the ElapsedTicks method works has led some people to the conclusion that it is not accurate, when they really just have a logic error in their code.

What is System diagnostics Stopwatch?

A Stopwatch instance can measure elapsed time for one interval, or the total of elapsed time across multiple intervals. In a typical Stopwatch scenario, you call the Start method, then eventually call the Stop method, and then you check elapsed time using the Elapsed property.

What is use of stopwatch in C#?

Stopwatch is a class in C# to measure the elapsed time. Use it to calculate the time a function took to execute. It is found under System. Diagnostics.


1 Answers

As per MSDN:

The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.

It uses a higher resolution / precision than DateTime.Now.

You can also check out these related links:

Environment.TickCount vs DateTime.Now

Is DateTime.Now the best way to measure a function's performance?

DateTime is good enough for precision to the second probably but anything beyond that I would recommend StopWatch.

like image 87
Kelsey Avatar answered Sep 18 '22 14:09

Kelsey