Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); // code to be timed goes here stopwatch.Stop(); Console.WriteLine("Elapsed Time: " + stopwatch.Elapsed.TotalSeconds + " seconds");
Stopwatch stopwatch1 = new Stopwatch(); Stopwatch stopwatch2 = new Stopwatch(); stopwatch1.Start(); // code to be timed with stopwatch1 goes here stopwatch1.Stop(); stopwatch2.Start(); // code to be timed with stopwatch2 goes here stopwatch2.Stop(); Console.WriteLine("Elapsed Time 1: " + stopwatch1.Elapsed.TotalSeconds + " seconds"); Console.WriteLine("Elapsed Time 2: " + stopwatch2.Elapsed.TotalSeconds + " seconds");In this example, we create two instances of the Stopwatch class and start them individually using the Start method. We can then execute our code to be timed between the Start and Stop calls for each stopwatch. Afterward, we stop each stopwatch and display the total elapsed time for each. The package library for the System.Diagnostics namespace is a part of the .NET Framework.