How to calculate the code execution time in C#?
How to calculate the code execution time in C#?
26513-Jun-2024
Updated on 13-Jun-2024
Home / DeveloperSection / Forums / How to calculate the code execution time in C#?
How to calculate the code execution time in C#?
Ashutosh Kumar Verma
13-Jun-2024Calculate the Code Execution Time
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#,
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 aTimeSpan
object 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#?