Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / XML

Get Time of Code Execution Using StopWatch

0.00/5 (No votes)
25 Jul 2011CPOL2 min read 20.2K  
How to get the time of code execution using stopwatch

During development of the application/product or after deployment of the application/product, there might be a situation where you want to find out how much time is taken by your code to execute? Is it too slow?

The answer to this problem is to make use of StopWatch class of System.Diagnostics namespace which is useful to find out the time taken to execute a given line of code. The class is helpful to find out how efficient code is developed by measuring the time of execution.

To understand how to use it, consider the below demo:

C#
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
//instead of this there is line of code that you are going to execute
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine(elapsedTime);
Console.ReadLine();

Stopwatch class has methods, Start() and Stop(). So the as name suggests, call start when you want to start your watch and call Stop when you want to stop the watch. Once you stop the watch, i.e., call stop method of the StopWatch class, you can get the value of time of execution by using Elapsed property of the class which returns TimeSpan object.

Output

There are also other important methods which are very useful. You can get the more infomation about those on the MSDN documentation over here: StopWatch Class.

Methods

  • StartNew - Initializes a new Stopwatch instance, sets the elapsed time property to zero, and starts measuring elapsed time.
  • Restart - Stops time interval measurement, resets the elapsed time to zero, and starts measuring elapsed time.
  • Reset - Stops time interval measurement and resets the elapsed time to zero.

Properties

  • ElapsedMilliseconds - Gets the total elapsed time measured by the current instance, in milliseconds.
  • ElapsedTicks - Gets the total elapsed time measured by the current instance, in timer ticks.

Advantage

  • Easy and simple to use.
  • Useful when you want to find out the time taken by the line of code to execute.
  • By using the class, there is no need of any third party tool because it is part of the .NET Framework.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)