You can calculate the execution time of a piece of code in C# using the Stopwatch class from the
System.Diagnostics namespace.
Example-
Here is a basic example to calculate the code execution time in c#,
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
// Create a Stopwatch instance
Stopwatch stopwatch = new Stopwatch();
// Start measuring time
stopwatch.Start();
// Operate whose execution time you want to measure
// For example, a loop that runs for some time
for (int i = 0; i < 5; i++)
{
// Print a message 5 time to increase the execution time
Console.WriteLine("Print text to take some execution time");
}
// Stop measuring time
stopwatch.Stop();
// Get the elapsed time
TimeSpan elapsedTime = stopwatch.Elapsed;
// Print the elapsed time in milliseconds
Console.WriteLine("\nExecution Time: " + elapsedTime.TotalMilliseconds + " ms");
Console.ReadLine();
}
}
In the above example-
We create an instance of Stopwatch named stopwatch.
We start the stopwatch using the Start() method.
Let’s create a task whose execution time we want to measure. This can be any code block or method.
We stop the stopwatch with the Stop() method.
We retrieve the elapsed time using the Elapsed property, which returns a
TimeSpan object representing the elapsed time.
Finally, we print the elapsed time to the console.
Output-
Print text to take some execution time
Print text to take some execution time
Print text to take some execution time
Print text to take some execution time
Print text to take some execution time
Execution Time: 0.7662 ms
Be sure to add the System.Diagnostics you will use; At the top of your file to use the Stopwatch class. This will provide an accurate measurement of the execution time of a specified rule.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Calculate the Code Execution Time
You can calculate the execution time of a piece of code in C# using the Stopwatch class from the
System.Diagnosticsnamespace.Example-
Here is a basic example to calculate the code execution time in c#,
In the above example-
We create an instance of
Stopwatchnamed stopwatch.We start the stopwatch using the
Start()method.Let’s create a task whose execution time we want to measure. This can be any code block or method.
We stop the stopwatch with the
Stop()method.We retrieve the elapsed time using the
Elapsedproperty, which returns aTimeSpanobject representing the elapsed time.Finally, we print the elapsed time to the console.
Output-
Be sure to add the System.Diagnostics you will use; At the top of your file to use the Stopwatch class. This will provide an accurate measurement of the execution time of a specified rule.
Also, Read: How to read file using StreamReader in C#?