Saturday, October 10, 2015

How to measure execution speed (time) in Milliseconds, Microseconds and Nanoseconds using Stopwatch in C# ?

There are situations in the programming world where developers need to measure the execution time of the code.
.NET framework provides Stopwatch class to measure elapsed time for an interval which has two properties ElapsedMilliseconds and ElapsedTicks.

ElapsedMilliseconds returns the time in milliseconds measured by current Stopwatch instance and can be used to measure time in milliseconds directly.
Here is a code snippet that measures time in milliseconds using Stopwatch .ElapsedMilliseconds .
Stopwatch watch = new Stopwatch();      
watch .Start();      

//Do some work       

watch .Stop();       
Console.WriteLine("Execution time : {0} ms", watch .ElapsedMilliseconds);
ElapsedTicks gets the total elapsed time measured by the current instance, in timer ticks. 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, milliseconds, microseconds or nanoseconds.
Here is a code snippet that measures the time in nanoseconds using Stopwatch.ElapsedTicks.
double frequency = Stopwatch.Frequency;
double nanosecPerTick = (1000 * 1000 * 1000) / frequency;
Stopwatch watch = new Stopwatch();
watch .Start();

//Do some work

double durNanosec = watchNow.ElapsedTicks * nanosecPerTick;
Console.WriteLine("Execution time : {0} ns", durNanosec);

Similarly ElapsedTicks property can be used to calculate microseconds Here is a simple code snippet that measures time in microseconds using Stopwatch.ElapsedTicks.
double frequency = Stopwatch.Frequency;
double microsecPerTick = (1000 * 1000) / frequency;
Stopwatch watch = new Stopwatch();
watch .Start();

//Do some work   

watch .Stop();
double durNanosec = watchNow.ElapsedTicks * microsecPerTick ;
Console.WriteLine("Execution time : {0} us", microsecPerTick );

No comments :

Post a Comment

Threaded Minds would love to hear from you !!!