Create Stopwatch Demo In Windows 10 UWP

In Windows 10 UWP, we have a Stopwatch class that you can use to time things easily in your apps and games. We can use it to get the time it takes for your code execution and optimize the code.

Let’s see the steps

Create a new Windows 10 UWP project.

Go to code behind page and add the following namespace,
 
using System.Diagnostics;

Create a new instance of Stopwatch as in the following code and start the timer using the Start method whenever you want, and also stop the timer using the following code.
  1. Stopwatch myStopWatch = newStopwatch();  
  2. myStopWatch.Start();  
  3. myStopWatch.Stop();  
Read the elapsed time from the instance you created. You can get the millisecond time also.

Full source code
  1. private void startbtn_Click(object sender, RoutedEventArgs e)   
  2. {  
  3.     myStopWatch.Start();  
  4. }  
  5.   
  6. private void stopbtn_Click(object sender, RoutedEventArgs e)   
  7. {  
  8.   
  9.     readings.Text = myStopWatch.Elapsed.ToString();  
  10.     string milliseconds = myStopWatch.ElapsedMilliseconds.ToString();  
  11.     myStopWatch.Stop();  
  12.   
  13. }  
Now run the app and see the output as in the following image.
 
demo

Tips

If you want to check the time taken in your application to executea  particular method, start the Stopwatch before your code executes and stop the time and print the elapsed time.


Similar Articles