C# C# Console

Calculate the Code Execution Time in C#

In this example we’ll learn How to measure execution time in C#.

As a programmer, we may need to find out the execution time used by a particular segment of the C# code, in order to optimize the performance. For example, we may want to know how much time is taken for reading multiple files in the file system, or fetching data from the database, or executing some business logic.

C# includes the Stopwatch class in the System.Diagnostics namespace, which can be used to accurately measure the time taken for code execution. You don’t need to use DateTime and calculate the time manually.

The following example measures the time taken for the execution of the for loop using StopWatch.

C# Code:

Output:

In the above example, first we create an instance of the Stopwatch class. The Start() method starts measuring time for executing the code until we call the Stop() method. The ElapsedMilliseconds property gets the total time measured by the current instance in milliseconds. Here, it will return the time taken in executing the for loop. (Please note that output showed is arbitrary.)

You can use the StartNew method to initialize an instance of Stopwatch. Also, you can start the counter immediately without creating an instance of Stopwatch using the new keyword.

C# Code:

The following example measures the total time taken for executing different code segments.

C# Code:

In the above example, the IsRunning() method checks whether a stopwatch is stopped or not (checks if the Stop() method has been called or not). If it is true then the Stop() method has not been called and the stopwatch is still running. If it is false, then the stopwatch is stopped. If a stopwatch is not running, then we can restart it and it will continue measuring time from where it stopped. Thus, we can measure the total execution time taken by different code segments.

The following example measures the time taken for executing each code segment.

C# Code:

In the above example, the Restart() method resets time to zero and starts measuring again using the same instance of Stopwatch. In this way, we can measure the execution time of different code segments using the same instance. We don’t need to create a separate instance for each code segment.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.