How to Get the Time Difference / Total run time of an application in C#
In the practical world of coding you’ll come around a situation when you want to know how long it takes your application to finish. This is very useful to judge the user experience. Depending on the time it takes you can also think of modifying the code to remove extra loops or time consuming methods so that the application can run faster.
Here is how I did it:
First at the beginning of every coding I have instantiated a new Date object:
DateTime _startdt = DateTime.Now;
and at the end of the application I again instantiate another date object:
DateTime _enddt = DateTime.Now;
Now, we can get the difference between them by just using Timespan class:
TimeSpan ts = _enddt – _startdt;
You can now display the difference in human readable format:
Console.WriteLine(“Total Time taken >> ” +
” Day :” + ts.Days +
” Hour(s) :” + ts.Hours +
” Minute(s) :” + ts.Minutes +
” Second(s) : ” + ts.Seconds +
” Milli Second(s) : ” + ts.Milliseconds
);
This is very short but useful trick for us. Hope you’ll like it.
