It is not uncommon for us to need to find out how long it takes for an application to run when written in C#. Luckily, there is an easy way to find out how long sections of your code are taking. If you want, there is a YouTube video of this short tutorial below.
We will need to add using System.Diagnostics; to our using block, to be able to use the StopWatch class.
Using the StopWatch class, we will Start() before the section of code we want to run, and Stop() after the section of code we need to measure.
Stopwatch sw = new Stopwatch(); sw.Start(); // start the stop watch for (int i = 0; i < 100; i++) { // slow down app so we have something to test Thread.Sleep(10); } sw.Stop(); // stop the stop watch Console.WriteLine("The application took {0} seconds to run.", sw.Elapsed);
This makes it easy for us to get the number of seconds that something has run.
Obviously, the code surrounding the start and stop methods would do something more than slow the application.
Of course, if we have something that is running over a period of time, and is more than just a few milliseconds we can use better methods to parse it out.
For example, we could use a TimeSpan object to parse the time better.
// Get the elapsed time as a TimeSpan value. TimeSpan ts = stopWatch.Elapsed; // Format and display the TimeSpan value. string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine(elapsedTime);
Hopefully no program of yours is taking hours to run, but that is a different story.
You can watch a tutorial here:
or Watch on YouTube.
Determine How Long Your App Takes to Run with StopWatch was originally found on Access 2 Learn