If at first you don't succeed, call it version 1.0

Contact Me

Sarvesh Kushwaha
Email : sarveshkushwaha@outlook.com

Total Pageviews

Powered by Blogger.

Friday, 15 August 2014

Calculate the Execution time of a Function in C# , Razor View, Aspx View


My previous article was on the how to do the performance profiling with Visual Studio. Using Visual Studio analyze tool we can profile a function , dynamic link library, project and solution.
Link of  - Performance Profiling with Visual Studio

Requirements :

  1. However if we want to see execution for a particular function , you definitely don't want to run the profiler for that.Although profiler is more sophisticated way.
  2. if you have any loop on your razor / aspx view of asp.net application ,through profile it wolld be difficult to calculate the time of that loop.
Solution :

Stopwatch class in System.Diagnostics namespace which provide set of methods and properties to calculate the elapsed time.

Example:

 In my MVC application i m calculating how much time my index function is taking to execute :

 public ActionResult Index()
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 100000000; i++)
            {

            }
            sw.Stop();
            Debug.WriteLine("Total Time taken by functions is {0}", sw.ElapsedMilliseconds);//using Elapsed Milliseconds
            return View();
        }

As you can see i have created the instance of stopwatch , starts that and stopped when my loop is getting over.Using Debug.Writeline to see the result in output window . you can use Console.Writeline for console application to see the result in console window.

Output :



















Note:
  1. Do not apply debugger in b/w  the code ,where you are using the stopwatch to measure the elapsed time .It will measure all the hurdles time of code.
Write less , Tell more. Happy Independence day :) 

1 comment: