Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); // some code to measure elapsed time for stopwatch.Stop(); Console.WriteLine("Elapsed time: " + stopwatch.Elapsed);
Stopwatch stopwatch = new Stopwatch(); int iterations = 100; long[] elapsedTimes = new long[iterations]; for (int i = 0; i < iterations; i++) { stopwatch.Start(); // some code to measure elapsed time for stopwatch.Stop(); elapsedTimes[i] = stopwatch.ElapsedMilliseconds; stopwatch.Reset(); } long minTime = elapsedTimes.Min(); long maxTime = elapsedTimes.Max(); long averageTime = elapsedTimes.Average(); Console.WriteLine("Min time: " + minTime); Console.WriteLine("Max time: " + maxTime); Console.WriteLine("Average time: " + averageTime);Both of these examples require the `System.Diagnostics` namespace, which is part of the .NET Framework. In summary, the Stopwatch class is a very useful tool for measuring the performance of code in csharp. Its accuracy and precision make it ideal for profiling and optimizing high-performance applications.