Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to measure execution time with C#

0.00/5 (No votes)
12 Dec 2011 1  
Code that measures a time interval as you would measure the execution time of a task

This C# code measures a time interval as you would measure the execution time of a task:


C#
DateTimestartTime=DateTime.Now;
Console.WriteLine("Started:{0",startTime);
//Executethetasktobetimed
for(int i=1;i<100000;i++)
{
    //Executethetasktobetimed
}
DateTime stopTime = DateTime.Now;
Console.WriteLine("Stopped:{0",stopTime);
TimeSpanelapsedTime=stopTime-startTime;
Console.WriteLine("Elapsed:{0",elapsedTime);
Console.WriteLine("inhours:"+elapsedTime.TotalHours);
Console.WriteLine("inminutes:"+elapsedTime.TotalMinutes);
Console.WriteLine("inseconds:"+elapsedTime.TotalSeconds);
Console.WriteLine("inmilliseconds:"+elapsedTime.TotalMilliseconds);

In C# 2.0, the same thing can be done as follows:


C#
Stopwatchwatch=newStopwatch();
watch.Start();
for(inti=1;i<1000000;i++)
{
    //Executethetasktobetimed
}
watch.Stop();
Console.WriteLine("Elapsed:{0",watch.Elapsed);
Console.WriteLine("Inmilliseconds:{0",watch.ElapsedMilliseconds);
Console.WriteLine("Intimerticks:{0",watch.ElapsedTicks);

For DateTime formatting options, refer to Format date and time.



alternatively you may also try http://msdn.microsoft.com/en-us/library/ff650674.aspx[^]

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here