introduction
I accidentally discovered the timer class Stopwatch of C#. It is especially suitable for measuring runtime, simple to use and accurate timing. It originates from a namespace and must be referenced using when used.
Classic examples
The following is an instance of one second delay to create the simplest instance.
(1) Start and stop method example
//Key click private void button_watch_Click(object sender, EventArgs e) { ("action_spent_time:" + watch(action)); } //Simulation of user functions takes time private void action() { (1000); } //Start and stop timers public static double watch(Action action) { //Instantiation Stopwatch stopWatch = new Stopwatch(); //Start the timer (); //User Tasks action(); //Stop the timer (); //Return timer time return ; }
Print display
action_spent_time:1014.7956
(2) Reset and restart method example
//Key click private void button_watch_Click(object sender, EventArgs e) { watchResetAndRestart(action); } //Simulation of user functions takes time private void action() { (1000); } //Reset and restart timer timer public void watchResetAndRestart(Action action) { //Instantiation Stopwatch stopWatch = new Stopwatch(); //Start the timer (); //User Tasks action(); ("action:"+ ); //Reset timer (); ("action reset:" + ); //Restart the timer (); //User Tasks action(); ("action Restart:" + ); //Reset timer (); } }
Print display:
action:1000.8485
action reset:0
action Restart:1009.2571
summary
Doesn't it feel very simple? Friends can use it.
1. In the example, you can see that the accuracy can be obtained by 0.1 microseconds. I think the calculation accuracy is very high. There is no need for such high precision to do calculations, or use other lower precision attributes, such as etc.
2. The functions of resetting reset() and stopping Stop() both stop the timer, but reset resets the time to 0, just pay attention to it here.
This is the end of this article about the usage of Stopwatch, a medium and high-precision timer in C#. For more related C# Stopwatch content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!