Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best way to measure the time cycles for a C# function?

Tags:

c#

Really, I'm looking for a good function that measure the time cycles accurately for a given C# function under Windows operating system. I tried these functions, but they both do not get accurate measure:

DateTime StartTime = DateTime.Now;      
TimeSpan ts = DateTime.Now.Subtract(StartTime);
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
//code to be measured
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed; 

Really, each time I call them, they give me different time for the same function

Please, if anyone know better way to measure time consuming accurately, please help me and thanks alot alot

like image 929
Duaa Avatar asked Jan 11 '11 02:01

Duaa


2 Answers

The Stopwatch is the recommended way to measure time it takes for a function to execute. It will never be the same from run to run due to various software and hardware factors, which is why performance analysis is usually done on a large number of runs and the time is averaged out.

like image 51
Adam Lear Avatar answered Sep 26 '22 15:09

Adam Lear


"they give me different time for the same function" - that's expected. Things fluctuate because you are not the only process running on a system.

Run the code you want to time in a large loop to average out any fluctuations (divide total time by the number of loops).

Stopwatch is an accurate timer, and is more than adequate timing for most situations.

const int numLoops = 1000000;   // ...or whatever number is appropriate

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();

for (int i = 0; i < numLoops; i++)
{
    // code to be timed...
}

stopWatch.Stop();
TimeSpan elapsedTotal = stopWatch.Elapsed;
double timeMs = elapsedTotal.TotalMilliseconds / numLoops;
like image 33
Mitch Wheat Avatar answered Sep 24 '22 15:09

Mitch Wheat