c sharp

C# Stopwatch

The stopwatch is the most-famous timepiece to calculate the total time passed during some task or activity. In real life, you may have encountered many situations like games and activities where the stopwatch gadgets have been used to calculate the elapsed time for two opponents. Computer technology is allowing us to use the stopwatch without a gadget to calculate the total time passed during some code execution. The C# “Stopwatch” class is one of the examples among all. In today’s article, we will be discussing the use of the “Stopwatch” class in unique C# codes to find out the total elapsed time. Let’s get started with the use of a “stopwatch” class in C# programming with the help of some basic examples. So, we have tried the “touch” query on the Ubuntu 20.04 shell to create a C# file of the “cs” extension at its end.

Example 01

We will open this newly generated file in the text editor of the Ubuntu 20.04 system to edit it. We have been starting our first illustration with the use of the “System” namespace or library in the C# code. It is utilized here to try some input and output functions in the program and make our program interactive in certain ways.

After this, we have been using the “Diagnostics” namespace of the “System” library in this program to make use of some of its debugging methods to check the efficiency of our code. Also, we have been using the “Threading” namespace to control the use of thread functions from the “thread” class. We have created a user-defined “Test” class and started it with the main() driver function. The driver function is creating an object “s” of class “Stopwatch” from the “Diagnostics” namespace using the “new” keyword along with the class name.

This object will be further utilized to call the built-in functions of the class “Stopwatch” by a dot product. As we want to find out the elapsed time of the code, we have to call the “Start” function of the Stopwatch class with the newly made object “s”. After calling this function, we have to add the code where we want to find out the elapsed time. So, we have started for a loop of 100 iterations. On each iteration, the “Sleep” function of the Thread class will be called to sleep for 100 milliseconds. After the loop ends, we have called the “Stop” function of the Stopwatch class. The “WriteLine” function from the Console class of the System namespace is here to display the total elapsed time using the “Elapsed()” function of class “Stopwatch”. The code is now complete and ready for execution.

We have saved this code in the file and used the “mcs” C# compiler command to debug the “stopwatch.cs” file. After compiling it, the “exe” file of this code got generated as shown. After running the “exe” file we have got the elapsed time displayed on our screen.

The output in the above example shows the time in milliseconds. To show time elapsed in seconds, we have to define the format in the output statement. So, we have been using this example to illustrate this simple concept. We have been using the very same code as shown in the image.  Within the WriteLine() function statement after the “for” loop and “Stop” function, we have been defining the format of elapsed time in hours, minutes, and seconds using “\\” signs.

After saving the updated code, we have been compiling it using the “mcs” C# compiler. It was successful and we have executed the compiled “exe” file. The time elapsed has been displayed in the specified format i.e. hours: minutes: seconds.

Example 02

We tend to use the “Start” function of the stopwatch class to get the current time because it is recommended to use when you need to check the program performance according to the tick count of the Linux. On the contrary, with the “StartNew” function of the stopwatch class, your code will be simpler by removing unwanted typing and diagnosing the code.

Now, Let’s take a look at the function “StartNew” of the Stopwatch class. So, open the same file and update the first line of the main driver function. We initialized a variable “s” and assigned it an instance of the StartNew() function from the “stopwatch” class. After this, we have been using the “for” loop to iterate 100 times and using the “Sleep” function of the “Thread” class within it to make the code sleep for 100 milliseconds.

As the loop runs 100 times, the milliseconds become 10000 milliseconds (i.e., 10 seconds.) The stopwatch has been completed using the “Stop” function of the same class and Console.WriteLine() function is here to display the elapsed time.

The execution of this code after the compilation shows the same result as we got above. There is no difference except the creation of a new instance for variable“s” using “StartNew”.

Example 03

Within this example, we will be discussing the “ElapsedTicks” instance of the “Stopwatch” class. It is used to count the total ticks elapsed for the particular time frame when the code has been executing. So, we will be updating our code to do so. We have been using the “Threading” namespace for the “System” library. So, within the main() method of the Test class, we have used the variable “S” to create a new object using the “StartNew” function of the Stopwatch class.

The object “s” has been used to get the ticks already elapsed using the instance “ElapsedTicks” and save to the log type variable “t1”. The “WriteLine()” function of the Console class is here to display the ticks already elapsed before the particular code execution using the long variable “t1”. After this, the “for” loop has been started to make use of the Sleep function from the Thread class to make the code sleep for 100 milliseconds in a total of 100 iterations.

After the loop is executed completely, another long variable “t2” has been declared that has been taking the count of already elapsed ticks via the instanced “ElapsedTicks”. The object “s” has been used to call the instance “ElapsedTicks”. The last WriteLine() function of the Console class is used to display the elapsed ticks counted in the variable “t2”.

After this code execution, we got the elapsed ticks before and after the loop execution. The total ticks elapsed during the execution of a loop can be counted by subtracting the first value t1 from the second value t2.

Conclusion

The use of the stopwatch gadget has been discussed in the introductory paragraph of this article. It has been demonstrated how a simple class can be utilized to find out the elapsed time without using a gadget while performing some C# code. The use of “Start” and “Stop” functions along with the “Elapsed” instance have been used for the stopwatch class to do so. We have altered the output by defining a new elapsed time format along with the “StartNew” function and also utilized the ElapsedTicks instance to get the total elapsed ticks during execution.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.