Updated April 13, 2023
Introduction to C# Stopwatch
Stopwatch classes in C# are used to calculate the time taken by a function to execute or we can say to measure the elapsed time. It is one of the most important features of C#. A stopwatch is useful in the optimization of codes by adding small bookmarks in the code and for using Stopwatch in C# we need to add System. Diagnostics library. Also, the user can perform continuous monitoring of the code performance. With the help of a stopwatch, users can have an accurate measurement of time if the operating system of the computer supports high-resolution counter for performance.
Let us have a look at the syntax of using a stopwatch in C# :
Stopwatch timer = new Stopwatch() ; // creating new instance of the stopwatch
timer.Start() ; // to start the timer in code
timer.Stop() ; // to stop the timer in code
The above three steps are necessary to use for implementing Stopwatch.
Examples of C# Stopwatch
Now we will see how a stopwatch works in C# through programming examples.
Example #1
Code:
using System ;
using System.Diagnostics ; // to use Stopwatch feature
using System.Threading ; // to perform multiple operations
class Demo_Stopwatch // Demo class for implementing the Stopwatch functionality
{
static void Main()
{
Stopwatch stopw = new Stopwatch() ;
stopw.Start() ;
for ( int i = 0 ; i < 100 ; i++ )
{
Thread.Sleep(2) ;
}
stopw.Stop() ;
Console.WriteLine( " Time elapsed: {0} " , stopw.Elapsed ) ;
}
}
Output :
As you can see in the above code that we are using System.Diagnostics library so that we can implement the stopwatch feature in the program. Initially, we are creating a class with the name “ Demo_Stopwatch ” in that class we are creating a new stopwatch with the name “ stopw ”. To start the stopwatch timer we are using Start() function. Now for how much time it will run we are using a for a loop by giving a sleep duration in the thread. After that, to stop the timing we are using a Stop() feature. To show the results we are using Console.WriteLine function to display the output time on the user screen.
Example #2
Code:
using System ;
using System.Diagnostics ; // to use Stopwatch feature
using System.Threading ; // to perform multiple operations
class Demo // Demo Class for Stopwatch demonstration
{
static void Main(string[] args)
{
Stopwatch stopW = new Stopwatch() ;
stopW.Start() ;
Thread.Sleep( 1000 ) ;
stopW.Stop() ;
TimeSpan tspan = stopW.Elapsed ;
string elapsedTime = String.Format ( " {0:00}:{1:00}:{2:00}.{3:00} " ,
tspan.Hours , tspan.Minutes , tspan.Seconds , tspan.Milliseconds / 10 ) ;
Console.WriteLine( " RunTime " + elapsedTime ) ;
}
}
Output :
As you can see in the above code that we are using System.Diagnostics library so that we can implement the stopwatch feature in the program. Initially, we are creating a class with the name “ Demo ” in that class we are creating a new stopwatch with the name “ stopW ”. To start the stopwatch timer we are using Start() function. Now for how much time it will run we are using a TimeSpan value named “ tspan ” by giving a sleep duration in the thread. So that we can get the elapsed time. After that, to stop the timing we are using a Stop() feature. Also, we are using string to format and then display the tspan values. In the time format, you can see we are using hours, minutes seconds, and milliseconds values. To show the results we are using Console.WriteLine function to display the output time on the user screen.
Example #3
Code:
using System ;
using System.Diagnostics ; // to use Stopwatch feature
using System.Threading.Tasks ; // for multiple task using threads
class MeasureTimeDemo // demo class for measuring the runtime
{
static void Main()
{
var time = StopwatchHelper.MeasureRunTime(() =>
{
for( var x = 0 ; x < 2 ; x++ )
{
using ( var task = Task.Delay( 100 ) )
{
task.Wait() ;
}
}
}) ;
Console.WriteLine( " Here is the elapsed time : " + time ) ;
}
static class StopwatchHelper
{
public static TimeSpan MeasureRunTime( Action codeToRun )
{
var watch = Stopwatch.StartNew() ;
codeToRun() ;
watch.Stop() ;
return watch.Elapsed ;
}
}
}
Output:
As you can see in the above code that we are using System.Diagnostics library so that we can implement the stopwatch feature in the program. Initially, we are creating a class with the name “MeasureTimeDemo ” in that class we are creating a var time with StopWatchHelper to measure the time. We are implementing a for loop inside the var time so that we can calculate the delay in time. To show the results we are using Console.WriteLine function to display the elapsed time on the user screen. After that, we have created a static class with the name “ StopWatchHelper ”. Inside this class, we declared a function with the name “ Time Span MeasureRunTime ” wherein the argument we are passing with the name Action CodeToRun. Therefore, in that function we are calling the StartNew() function to start the watch timer after that CodeToRun is being called and finally, we are calling the Stop() function so that we can calculate the elapsed time between the event. At the end of the code, we are returning the watch. Elapsed which will be printed on the user screen through Console.WriteLine command.
Conclusion
With the help of the stopwatch in C#, a user can easily measure the time interval for any particular event including multiple time intervals. All we have to do is call the start and stop methods than by using the elapsed feature we can calculate time intervals.
Recommended Articles
This is a guide to C# Stopwatch. Here we discuss how a stopwatch works in C# through programming examples for better understanding. You may also have a look at the following articles to learn more –